if os.chdir(path+"micro")==True:
os.chdir(path+"micro")
else:
os.mkdir(path+"micro")
os.chdir(path+"micro")
when I use this method it gives me an error and says file exitsts why can't I access that file
If I understand your question correctly, this code is for you:
if os.path.exists(path+"micro"):
os.chdir(path+"micro")
else:
os.mkdir(path+"micro")
os.chdir(path+"micro")
Your code was incorrect because as you can see from the documentation os.chdir does not return any value, but is used to change the current working directory to the given path. Returns None in all the cases. For this reason your code gave an error.
Instead you need the os.path.exists method which return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
I think what you are trying to do is:
dir = os.path.join(path, "micro")
if not os.path.isdir(dir):
os.mkdir(dir)
os.chdir(dir)
os.chdir(path+"micro") This does not return false if the path doesn't exist. It rather gives an error. Also writing path + "mirco" is not a good practice either. The standard way is using os.path.join(path, "micro") because it handles choosing "/" or "\" according to the os it is running on.
So these are some alternatives that you might try.
Alternative 1:
dir = os.path.join(path, "micro")
if not os.path.exists(dir):
os.mkdir(dir)
os.chdir(dir)
Alternative 2:
dir = os.path.join(path, "micro")
try:
os.chdir(dir)
except:
os.mkdir(dir)
os.chdir(dir)
Related
I am running a script to uninstall a program and to finish the process, I am checking if the applicable directories get deleted as expected. I have the following:
D_PATHS = (
r'C:\ProgramFiles\D1\FolderA',
r'C:\ProgramFiles\D1\FolderB',
r'C:\ProgramFiles\D1\FolderC',
)
for path in D_PATHS:
self.info('Deleting %s', path)
if os.path.exists:
warnings.warn(f'The following directory still exists: {path}')
else:
print(f'Removed all required directories')
When I run the script, it always throws the warning that the directories still exist, even if they don't. What am I doing wrong? Please excuse my very limited knowledge of coding. I know there's probably an easy answer that I am not understanding.
os.path.exists is a function, you need to give it an argument:
...
if os.path.exists(path):
print("Still exists")
...
If you want to print a warning for each directory that exists, then you should set a boolean flag to decide at the end whether to print the "removed all required directories" message.
dirs_exist = False
for path in D_PATHS:
self.info('Deleting %s', path)
if os.path.exists(path):
warnings.warn(f'The following directory still exists: {path}')
dirs_exist = True
if not dirs_exist:
print(f'Removed all required directories')
The alternative, if you only want to warn about the first directory that still exists, is to break from the for loop, in which case you can use an else clause on your for loop for printing the message if no break was encountered:
for path in D_PATHS:
self.info('Deleting %s', path)
if os.path.exists(path):
warnings.warn(f'The following directory still exists: {path}')
break
else:
print(f'Removed all required directories')
Note that despite the messages saying "Deleting", the code that you have shown here is not actually deleting anything. Presumably you have done so earlier in your code.
It may be possible that you dont have the permission so you can not delete them.
1.Generate a python.exe with pyinstaller .
2.Right Click and click the option "run as administrator"
I've see this question about how to make a folder writable.
But how do I query for write permissions on a folder?!?!
On a directory in C:\Program Files\... where I clearly get IOError: [Errno 13] Permission denied every method I tried seems to clearly say ALL GOOD! ... (probably created by Admin; other dirs in Program Files can be written no problem)
For instance os.access also says fine. The docs tells me about EAFP and true: When I try to write a dummy file I get the wanted information but actually I'd like to not go that far.
On the other hand? How bad is it actually? Vaguely assuming I'd dare to do something like this:
import os
import uuid
def write_dir_test(path):
dummypath = os.path.join(path, str(uuid.uuid4()))
try:
with open(dummypath, 'w'):
pass
os.remove(dummypath)
return True
except IOError:
return False
It "feels" kinda dirty. But actually: Is it?
Is there a better way?
To answer your question "how bad" is it?
Well, I first found the question you've linked to, then implemented almost exactly what you have (difference: I do str(uuid.uuid4()+".txt", I write a dummy string to the file, and I catch OSError instead of IOError, but other than that, I'm doing exactly the same thing:
def is_writable(dirpath):
if sys.platform.startswith("linux"):
return os.access(dirpath, os.W_OK)
try:
test_file = os.path.join(dirpath, str(uuid.uuid4()) + ".txt")
with open(test_file, "w") as test:
test.write("hello")
os.unlink(test_file)
return True
except OSError as e:
print(e)
return False
For "production" use, I'd just remove the print(e).
You avoid some problems with tempfile by using uuid.
My version checks the platform, to default to os.access when on Linux, where it works.
Corner cases like "the directory is writable, but the disk is full" can often be ignored (you won't be writing to this directory anytime soon!).
To sum up — how bad? I'd say: relax, it's pretty good.
import os
path = "D:\uda\prank\photo"
def rename_files():
print os.path.exists(path)
if os.path.exists(path):
print("exists")
file_list = os.listdir(path)
print(file_list)
else:
print("No luck")
I'm trying to print a list of filenames using os.listdir method, however nothing appeared even from "exists" or "No luck", so what could be happening over here? I thought it was because of administrator's restriction, however now I'm pretty sure that won't bother at all. Please help!
You have defined a function (rename_files), but never call it (at least from the posted code).
Let's say on my filesystem the following directory exists:
/foo/bar/
In my python code I have the following path:
/foo/bar/baz/quix/
How can I tell that only the /foo/bar/ part of the path exists?
I can walk the path recursively and check it step by step, but is there an easier way?
No easy function in the standard lib but not really a difficult one to make yourself.
Here's a function that takes a path and returns only the path that does exist.
In [129]: def exists(path):
...: if os.path.exists(path): return path
...: return exists(os.path.split(path)[0])
...:
In [130]: exists("/home/sevanteri/src/mutta/oisko/siellä/jotain/mitä/ei ole/")
Out[130]: '/home/sevanteri/src'
I think a simple while loop with os.path.dirname() will suffice the requirement
path_string = '/home/moin/Desktop/my/dummy/path'
while path_string:
if not os.path.exists(path_string):
path_string = os.path.dirname(path_string)
else:
break
# path_string = '/home/moin/Desktop' # which is valid path in my system
I don't actually get your requirements as whether you want every path to be checked or upto some specific level.But for simple sanity checks you can just iterate through the full path create the paths and check the sanity.
for i in filter(lambda s: s, sample_path.split('/')):
_path = os.path.join(_path, i)
if os.path.exists(_path):
print "correct path"
Well, I think the only way is to work recursively... Though, I would work up the directory tree. The code isn't too hard to implement:
import os
def doesItExist(directory):
if not os.path.exists(directory):
doesItExist(os.path.dirname(directory)
else:
print "Found: " + directory
return directory
Actually need to go some path and execute some command and below is the code
code:
import os
present_working_directory = '/home/Desktop/folder'
presently i am in folder
if some_condition == true :
change_path = "nodes/hellofolder"
os.chdir(change_path)
print os.getcwd()
if another_condition == true:
change_another_path = "nodes"
os.chdir(change_another_path)
print os.getcwd()
**Result**:
'/home/Desktop/folder/nodes/hellofolder'
python: [Errno 1] No such file or directory
Actually whats happening here is when i first used os.chdir() the directory has changed to
'/home/Desktop/folder/nodes/hellofolder',
but for the second one i need to run a file by moving to one folder back that is
'/home/Desktop/folder/nodes'
So can anyone let me how to move one folder back in python
Just like you would in the shell.
os.chdir("../nodes")
Here is a very platform independent way to do it.
In [1]: os.getcwd()
Out[1]: '/Users/user/Dropbox/temp'
In [2]: os.path.normpath(os.getcwd() + os.sep + os.pardir)
Out[2]: '/Users/user/Dropbox/'
Then you have the path, and you can chdir or whatever with it.
Just call
os.chdir('..')
the same as in any other language :)
Exact answer for your question is os.chdir('../')
Use case:
Folder1:
sub-folder1:(you want to navigate here)
Folder2:
sub-folde2:(you are here)
To navigate to sub-folder1 from sub-folder2, you need to write like this
"../Folder1/sub-folder1/"
then, put it in os.chdir("../Folder1/sub-folder1/").
think about using absolute paths
import os
pwd = '/home/Desktop/folder'
if some_condition == true :
path = os.path.join(pwd, "nodes/hellofolder")
os.chdir(path)
print os.getcwd()
if another_condition == true:
path = os.path.join(pwd, "nodes")
os.chdir(path)
print os.getcwd()
My problem was fixed with this command
first import os and after add
os.path.normpath(os.path.abspath(__file__) + os.sep + os.pardir)
The answers mentioned above are correct. The following is more a
It usually happens when your Python script is in a nested directory and you want to go one level up from the current working directory to maybe let's say load a file.
The idea is to simply reformat the path string and prefix it with a '../'. So an example would be.
'../current_directory/' + filename
This format is similar to when used in a terminal. Whenever in doubt fire up a terminal and experiment with some commands. The format is reflected in the programming language.
Define this function in your script and call it whenever you want to go back just by one folder:
import os
def dirback():
m = os.getcwd()
n = m.rfind("\\")
d = m[0: n+1]
os.chdir(d)
return None