简体   繁体   中英

glob- python sorted list of file

If in my directory I have a list of filenames like: "1_r.png","1_l.png","2_r.png","2_l.png","3_r.png","3_l.png".

How can I use glob() to sort them? I have some idea like

glob.glob('{path}/*{suffix}'), 
        key=lambda x: int(...):

It the suffix is "_l.png" I want to list the files that contain "_l.png" only. I do not know how can I define the key to sort it.

As I understand it you want two things to be done:

  • filter your file to contain only files with the ending "_l.png"
  • sort your file list

A very easy way to achieve this is this:

sorted(glob.glob("*_l.png"))

UPDATE:

To sort the files by their number as an integer you need to extract the number from the name.

# get all png files
lst = glob.glob("*_l.png")

# extract the number and create a tuple
lst = [(int(s.split("_")[0]), s) for s in lst]

# sort the tuple and create a new list with only the filename
lst = [x[1] for x in sorted(lst)]

You can look into natsort if you need it sorted in natural order, https://pypi.org/project/natsort/ .

Example:

from natsort import natsorted
#a= ["1_r.png","1_l.png","2_r.png","2_l.png","3_r.png","3_l.png"]
a= ["3_r.png","1_l.png","2_r.png","2_l.png","1_r.png","3_l.png"]
print(natsorted(a))

output:

['1_l.png', '1_r.png', '2_l.png', '2_r.png', '3_l.png', '3_r.png']

It can used with glob like,

for file in natsorted(glob.glob("*.png")):
    print(file)

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