I'm populating a tkinter listbox with files from a directory. The names of the files all start with a number from 01 - n. When I view the files in the directory they appear in numerical order. However, when I load the files into a listbox they aren't ordered numerically. I can change the leading numbers around, but the same files will always appear in the same spot.
I'm just using simplified item names to keep things simple with this example. It still shows that they're not being sorted alphabetically nor numerically.
The list should appear as the following in my listbox
01. itemA
02. itemB
03. itemC
04. itemD
But it appears as:
01. itemA
04. itemD
02. itemB
03. itemC
I can change the leading numbers around, but the files will always populate in the same order (by name, not number). The strange thing is, it's not even alphabetical order.
I've used this
i = 0
for filename in os.listdir(directory):
fileList.insert(i, filename)
i = i + 1
And this
for filename in os.listdir(directory):
fileList.insert(END, filename)
Both result in the same thing.
The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.
What is filenotfounderror. It is a system message that the compiler throws when you are trying to execute a command that requires a file that the system cannot find. It can be for various reasons like – wrong file path specified, the file is present in another directory, or an extension error.
By default, the list of files returned by os. listdir() is in arbitrary order. Sorting directory contents returns a list of all files and subdirectories within the current directory in alphabetic order.
The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With