I try since a while to get all names of files with a certain extension (let's say .txt) in a folder. I found a lot of close topics online but never what I wanted to do.
The closest I've reach is by using:
listFiles = glob.glob(sourdir '/*.txt')
or
files = fnmatch.filter(os.listdir(sourdir "/"), "*.txt")
or
[s for s in os.listdir(sourdir "/") if s.endswith('.txt')]
which gives me all the .txt files in a certain folder. HOWEVER, it automatically sort the files ! In my folder I have :
file0.txt, file1.txt, file2.txt, file3.txt, ...
And with anything that give me those files I have something like :
file0.txt, file1.txt, file10.txt, file11.txt, ...
I just want to read the name of the file in the same order in which they are in the folder ! How is it so hard to do simple things..
If I do os.listdir(sourdir "/")[i] in a loop, I can see that the listdir check the file in the correct order not the sorted one. However I didnt not success to use "os.listdir(sourdir "/")[i]" in a loop AND filtering by .txt in the same time.
If someone could help me I really don't know what to do now
CodePudding user response:
I am new to StackOverflow, unable to comment. As Jarmod stated, you either "care" or "don't care" if they are sorted. You seem to care.
So, if you are looking for the most efficient code, this answer will not please you.
>>> import os
>>> import fnmatch
>>> path = '/temp/'
>>> unsorted_list = [file_name for file_name in next(os.walk(path))[2]]
>>> unsorted_filtered_list = fnmatch.filter(unsorted_list,'*.txt')
>>> print(unsorted_list)
['3.txt', '7.yyy', '2.txt', '5.txt', '1.txt', '4.txt', '6.ttt', '1.aaa']
>>> print(unsorted_filtered_list)
['3.txt', '2.txt', '5.txt', '1.txt', '4.txt']
CodePudding user response:
Explaining my problem helped me to aim at what to do to solve it, so a workaround was to sort by date of creation of files, which I finally managed to do with :
sorted_by_mtime_ascending = sorted(listTdmsFiles, key=lambda t: os.stat(t).st_mtime)