Dylan Moore Dylan Moore - 1 year ago 76
Python Question

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):
if file.split(".")[1] == 'zip':

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.

Answer Source

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'):

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download