Ordered by os.listdir () in python

How to add files to the list by order

In my directory, I have the following files: slide1.xml, slide2.xml, slide3.xml ... slide13.xml

os.listdir(path) does not return me a list by order

I tried this way

 files_list = [x for x in sorted(os.listdir(path+"/slides/")) if os.path.isfile(path+"/slides/"+x)] 

output: ['slide1.xml', 'slide10.xml', 'slide11.xml', 'slide12.xml', 'slide13.xml', 'slide2.xml', 'slide3.xml', 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml', 'slide8.xml', 'slide9.xml']

+7
python file order
source share
2 answers

Key Sort:

 import re files = ['slide1.xml', 'slide10.xml', 'slide11.xml', 'slide12.xml', 'slide13.xml', 'slide2.xml', 'slide3.xml', 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml', 'slide8.xml', 'slide9.xml'] ordered_files = sorted(files, key=lambda x: (int(re.sub('\D','',x)),x)) 

gives ['slide1.xml', 'slide2.xml', 'slide3.xml', 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml', 'slide8.xml', 'slide9.xml', 'slide10.xml', 'slide11.xml', 'slide12.xml', 'slide13.xml']

+9
source share

You can use your own sort function.

 def custom_sort(x, y): pass #your custom sort files_list = [x for x in sorted(os.listdir(path+"/slides/"), cmp=custom_sort) if os.path.isfile(path+"/slides/"+x)] 

doc

also check natsort

+1
source share

All Articles