0

So my program is looking through the files in the current folder 'sample_files' and printing them out. However, when the files are being printed out they are not in numerical order. Here is the contents of the 'sample_files' folder:

sample_1.txt

sample_2.txt

sample_3.txt

sample_3.txt

...

sample_10.txt

How my program prints these out is that it goes 'sample_1.txt', 'sample_10.txt', 'sample_2.txt', etc. Basically, the digits in the tens go right after 1 when being printed out. Here is my code:

import os

# Get files in current directory
files = os.listdir()    

# Loop through files
for file in files:
    print(file)

I was also looking around a bit and some people have said to use the sorted() function to organize these files but I updated my code and I still get the same results.

import os

# Get files in current directory
files = os.listdir()    
sorted_files = sorted(files)

# Loop through files
for file in sorted_files:
    print(file)

Maybe there's something I'm doing wrong but I'm not sure.

0 Answers0