Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered os.listdir() in python [duplicate]

Tags:

python

file

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']

like image 472
Pythonizer Avatar asked May 18 '14 17:05

Pythonizer


People also ask

Does OS Listdir go in order?

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.

What is OS Listdir ()?

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.

What does OS Listdir return?

This method returns the list of files and directories in a given path.

Is Scandir faster than Listdir?

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.


2 Answers

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']

like image 63
Daniel Avatar answered Oct 06 '22 11:10

Daniel


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

like image 44
Andres Avatar answered Oct 06 '22 12:10

Andres