1

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

2
  • 2
    glob.glob will only return file that do exist what are you trying to do by testing if the file exist ? Commented Sep 14, 2011 at 20:12
  • "file print does not happen"? There are two print statements. Can you be more specific? Commented Sep 14, 2011 at 20:12

4 Answers 4

3

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"
Sign up to request clarification or add additional context in comments.

Comments

3

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"

Comments

1

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"

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.