Search code examples
pythonfiledirectorylistdir

os.listdir() not printing out all files


I've got a bunch of files and a few folders. I'm trying to append the zips to a list so I can extract those files in other part of the code. It never finds the zips.

for file in os.listdir(path):
     print(file)
     if file.split(".")[1] == 'zip':
     reg_zips.append(file)

The path is fine or it wouldn't print out anything. It picks up the same files each time but will not pick up any others. It picks up about 1/5th of the files in the directory.

At a complete loss. I've made sure that some weird race condition with the file availability isn't the problem by putting a time.sleep(3) in the code. Didn't solve it.


Solution

  • It's possible your files have more than one period in them. Try using str.endswith:

    reg_zips = []
    for file in os.listdir(path):
         if file.endswith('zip'):
             reg_zips.append(file)
    

    Another good idea (thanks, Jean-François Fabre!) is to use os.path.splitext, which handles the extension quite nicely:

    if os.path.splitext(file)[-1] == '.zip':
        ... 
    

    Am even better solution, I recommend with the glob.glob function:

    import glob
    reg_zips = glob.glob('*.zip')