python if file does not exist fails
so I have a loop that checks folder if it contains *.zip file
for file in glob.glob( os.path.join(rootdir, '*.zip')):
print "zip", file
#Check if file does not exist
if not os.path.exists(file):
print "No files"
#return
else:
some code
Now if file exist else works, but 开发者_运维知识库if there is no zip file print does not happen
Any suggestions?? Thank you
If there is no zip file in that folder, the for loop never executes.
Just like
for i in []:
print "Hello"
doesn't print anything because there are no elements to iterate over.
If you need that error message, you can do this:
filelist = glob.glob(os.path.join(rootdir, '*.zip'))
if filelist:
for f in filelist:
# some code
else:
print "No files"
If there are no zip files then you are looping over an empty list, try something like this:
files = glob.glob( os.path.join(rootdir, '*.zip'))
if len(files) != 0:
for file in files:
print "zip", file
#Check if file does not exist
if not os.path.exists(file):
print file, "does not exist"
#return
else:
some code
else:
print "No files"
The glob()
file returns any matches it finds. If it finds no matches for the pattern you provide, then it returns the empty list: []
. This is different from what the shell glob patterns do! In most shells, foo*
when no files start with foo*
will just give the word foo*
to the command; but that is not what glob()
does.
If no files exist, then your loop won't run at all. The test os.path.exists(file) will always be true (unless other processes are deleting files as you are running the loop) because otherwise, glob wouldn't list is as a file.
files = glob.glob( os.path.join(rootdir, '*.zip'))
for file in files:
print "zip", file
if len(files) == 0:
print "no files"
精彩评论