How to add files into a list by order
In my directory i have the following files: slide1.xml, slide2.xml, slide3.xml ... slide13.xml
os.listdir(path)
doesn't return me a list by order
I've 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']
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.
listdir() method in python is used to get the list of all files and directories in the specified directory. If we don't specify any directory, then list of files and directories in the current working directory will be returned.
This method returns the list of files and directories in a given path.
This subdirs() function will be significantly faster with scandir than os. listdir() and os. path. isdir() on both Windows and POSIX systems, especially on medium-sized or large directories.
Sort by key:
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']
You may want to 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
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