简体   繁体   中英

How to sort file names in a particular order using python

Is there a simple way to sort files in a directory in python? The files I have in mind come in an ordering as

file_01_001
file_01_005
...
file_02_002
file_02_006
...
file_03_003
file_03_007
...
file_04_004
file_04_008

What I want is something like

file_01_001
file_02_002
file_03_003
file_04_004
file_01_005
file_02_006
...

I am currently opening them using glob for the directory as follows:

for filename in glob(path):    
    with open(filename,'rb') as thefile:
        #Do stuff to each file

So, while the program performs the desired tasks, it's giving incorrect data if I do more than one file at a time, due to the ordering of the files. Any ideas?

As mentioned, files in a directory are not inherently sorted in a particular way. Thus, we usually 1) grab the file names 2) sort the file names by desired property 3) process the files in the sorted order.

You can get the file names in the directory as follows. Suppose the directory is "~/home" then

import os

file_list = os.listdir("~/home")

To sort file names:

#grab last 4 characters of the file name:
def last_4chars(x):
    return(x[-4:])

sorted(file_list, key = last_4chars)   

So it looks as follows:

In [4]: sorted(file_list, key = last_4chars)
Out[4]:
['file_01_001',
 'file_02_002',
 'file_03_003',
 'file_04_004',
 'file_01_005',
 'file_02_006',
 'file_03_007',
 'file_04_008']

To read in and process them in sorted order, do:

file_list = os.listdir("~/home")

for filename in sorted(file_list, key = last_4chars):    
    with open(filename,'rb') as thefile:
        #Do stuff to each file

A much better solution is to use Tcl's "lsort -dictionary":

from tkinter import Tcl
Tcl().call('lsort', '-dict', file_list)

Tcl dictionary sorting will treat numbers correctly, and you will get results similar to the ones a file manager uses for sorting files.

i have similar issue, but little diferent, can we sort subfolders in a folder and then every subfolder has a png file such as

['1.2.392.200036.9116.4.2.7383.1467.20210811020536539.1.2', '1.2.392.200036.9116.4.2.7383.9500.20210811020536560.1.4', '1.2.392.200036.9116.4.2.7383.7724.20210811020536578.1.6', '1.2.392.200036.9116.4.2.7383.9962.20210811020536605.1.9', '1.2.392.200036.9116.4.2.7383.7334.20210811020536551.2.3', '1.2.392.200036.9116.4.2.7383.2169.20210811020536569.2.5', '1.2.392.200036.9116.4.2.7383.3478.20210811020536587.2.10', '1.2.392.200036.9116.4.2.7383.3358.20210811020536596.9.11',

I want to sort folder with last 2 didgits and then very folder has a png file inside it, so i want to acces it in assending order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM