Python os.listdir() keeps skipping over some files?

python, scripting, shell

Solution

You can try to use the built in sorted method, eg

for line in sorted(os.listdir(d)):
    f.write(line + "\n")

Here's some more information from python documentation that you might find helpful: https://docs.python.org/2/library/os.html

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Problem

I have written a Python script for writing out all the file names in a given directory to a file for processing, and it works perfectly on my machine. But when I try to run it on the target machine, it skips some of the files. Here's a shell of the code I am using: ``` for line in os.listdir(d): f.write(line + "\n") ``` As I said, this works as advertised on my system, but not on the target system. The data is the same; I transferred it from the target system to mine for preliminary testing while writing the script, and I've inspected both data sources to verify that nothing got lost in the transfer. Output from my system looks like: ``` filename.f0000 filename.f0001 filename.f0002 filename.f0003 ... ``` But output from the target system looks like: ``` filename.f0000 filename.f0003 filename.f0008 filename.f0017 ... ``` I am on a 64-bit Windows PC running Cygwin, and it has Python version 2.7.5 installed. The target system is a Cray XK7 running OpenSuse, and it has Python version 2.6.8 installed. Could this be a difference between the two versions of Python, or rather the two different operating systems?

Original source