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).
Related
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)
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.
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
Essentially, I'm wondering if the top answer given to this question can be implemented in Python. I am reviewing the modules os, os.path, and shutil and I haven't yet been able to find an easy equivalent, though I assume I'm just missing something simple.
More specifically, say I have a directory A, and inside directory A is any other directory. I can call os.walk('path/to/A') and check if dirnames is empty, but I don't want to make the program go through the entire tree rooted at A; i.e. what I'm looking for should stop and return true as soon as it finds a subdirectory.
For clarity, on a directory containing files but no directories an acceptable solution will return False.
maybe you want
def folders_in(path_to_parent):
for fname in os.listdir(path_to_parent):
if os.path.isdir(os.path.join(path_to_parent,fname)):
yield os.path.join(path_to_parent,fname)
print(list(folders_in("/path/to/parent")))
this will return a list of all subdirectories ... if its empty then there are no subdirectories
or in one line
set([os.path.dirname(p) for p in glob.glob("/path/to/parent/*/*")])
although for a subdirectory to be counted with this method it must have some file in it
or manipulating walk
def subfolders(path_to_parent):
try:
return next(os.walk(path_to_parent))[1]
except StopIteration:
return []
I would just do as follows:
#for example
dir_of_interest = "/tmp/a/b/c"
print(dir_of_interest in (v[0] for v in os.walk("/tmp/")))
This prints True or False, depending if dir_of_interest is in the generator. And you use here generator, so the directories to check are generated one by one.
You can break from the walk anytime you want. For example, this brakes is a current folder being walked, has no subdirectories:
for root, dirs, files in os.walk("/tmp/"):
print(root,len(dirs))
if not len(dirs): break
Maybe this is in line with what you are after.
Try this:
#!/usr/local/cpython-3.4/bin/python
import glob
import os
top_of_hierarchy = '/tmp/'
#top_of_hierarchy = '/tmp/orbit-dstromberg'
pattern = os.path.join(top_of_hierarchy, '*')
for candidate in glob.glob(pattern):
if os.path.isdir(candidate):
print("{0} is a directory".format(candidate))
break
else:
print('No directories found')
# Tested on 2.6, 2.7 and 3.4
I apparently can't comment yet; however, I wanted to update part of the answer https://stackoverflow.com/users/541038/joran-beasley gave, or at least what worked for me.
Using python3 (3.7.3), I had to modify his first code snippet as follows:
import os
def has_folders(path_to_parent):
for fname in os.listdir(path_to_parent):
if os.path.isdir(os.path.join(path_to_parent, fname)):
yield os.path.join(path_to_parent, fname)
print(list(has_folders("/repo/output")))
Further progress on narrowing to "does given directory contain any directory" results in code like:
import os
def folders_in(path_to_parent):
for fname in os.listdir(path_to_parent):
if os.path.isdir(os.path.join(path_to_parent, fname)):
yield os.path.join(path_to_parent, fname)
def has_folders(path_to_parent):
folders = list(folders_in(path_to_parent))
return len(folders) != 0
print(has_folders("the/path/to/parent"))
The result of this code should be True or False
I have a simple directory structure:
rootdir\
subdir1\
file1.tif
subdir2\
file2.tif
...
subdir13\
file13.tif
subdir14\
file14.tif
If I call:
import os
print os.listdir('absolute\path\to\rootdir')
...then I get what you'd expect:
['subdir1', 'subdir2', ... 'subdir13', 'subdir14']
Same thing happens if I call os.listdir() on those sub-directories. For each one it returns the name of the file in that directory. No problems there.
And if I call:
import os
for dirpath, dirnames, filenames in os.walk('absolute\path\to\rootdir'):
print filenames
print dirnames
...then I get what you'd expect:
[]
['subdir1', 'subdir2', ... 'subdir13', 'subdir14']
['file1.tif']
[]
['file2.tif']
[]
...
But here's the strangeness. When I call:
import os
for dirpath, dirnames, filenames in os.walk('absolute\path\to\rootdir'):
print filenames
print dirnames
print dirpath
...it never returns, ever. Even if I try:
print [each[0] for each in os.walk('absolute\path\to\roodir')]
...or anything of the sort. I can always print the second and third parts of the tuple returned by os.walk(), but the moment that I try to touch the first part the whole thing just stops.
Even stranger, this behavior only appears in scripts launched using the shell. The command line interpreter acts normally. I'm curious, what's going on here?
-----EDIT-----
Actual code:
ALLOWED_IMGFORMATS = [".jpg",".tif"]
def getCategorizedFiles(pathname):
cats = [each[0] for each in os.walk(pathname) if not each[0] == pathname]
ncats = len(cats)
tree = [[] for i in range(ncats+1)]
for cat in cats:
catnum = int(os.path.basename(cat))
for item in os.listdir(cat):
if not item.endswith('.sift') and os.path.splitext(item)[-1].lower() in ALLOWED_IMGFORMATS:
tree[catnum].append(cat + '\\' + item)
fileDict = {cat : tree[cat] for cat in range(1,ncats+1)}
return fileDict
----EDIT 2----
Another development. As stated above, this problem exists when the code is in scripts launched from the shell. But not any shell. The problem exists with Console 2, but not the Windows command prompt. It also exists when the script is launched from java (how I originally came across the problem) like so: http://www.programmersheaven.com/mb/python/415726/415726/invoking-python-script-from-java/?S=B20000
I've never really trusted os.walk(). Just write your own recursive stuff. It's not hard:
def contents(folder, l): # Recursive, returns list of all files with full paths
directContents = os.listdir(folder)
for item in directContents:
if os.path.isfile(os.path.join(folder, item)):
l.append(os.path.join(folder, item))
else:contents(os.path.join(folder, item), l)
return l
contents = contents(folder, [])
contents will then be a list of all the files with full paths included. You can use os.split() if you like to make it a little easier to read.
Knowing how this works eliminates the uncertainty of using os.walk() in your code, which means you'll be able to identify if the problem in your code is really involved with os.walk().
If you need to put them in a dictionary (because dictionaries have aliasing benefits, too), you can also sort your files that way.