Files from directory being pulled in wrong order with python [duplicate] Files from directory being pulled in wrong order with python [duplicate] tkinter tkinter

Files from directory being pulled in wrong order with python [duplicate]


os.listdir doesn't guarantee any ordering of the contents of a directory. If you want the items to be sorted, just sort them using the builtin sorted function (with an appropriate key function if necessary).


Try this.

for index, filename in enumerate(sorted(os.listdir(directory))):        print '{0:02d}. {1}'.format(index + 1, filename)

In the event that the number is part of the filename go with @FabienAndre's comment.

for filename in sorted(os.listdir(directory)):        print filename