os.scandir()
returns the files in whichever order the OS returns them. This is the closest you can get to "original order" if you mean the order they are stored in the directory.
import os
import csv
with open('file.csv', 'w') as output:
writer = csv.writer(output)
for file in os.scandir():
writer.writerow([file.name])
Using a CSV file for a simple single column of text is slightly silly, but perhaps your users are unsophisticated (or perhaps your file names are really sophisticated, and you need to correctly cope with file names with newlines in them etc).
Your picture looks like the files are simply in alphabetical order, which is how some file browsers will display them. os.listdir()
will produce the files in alphabetical order, or just apply sorted()
to the list you got from os.scandir()
if you want to apply some sort of custom sort order, such as by creation date (if your OS provides that) or latest modification date. (The objects returned by os.scandir
have a .stat
member which contains this information.)