ordered with glob.glob in python [duplicate]

风格不统一 提交于 2019-12-19 09:04:21

问题


I have a list of file:

foo_00.txt
foo_01.txt
foo_02.txt
foo_03.txt
foo_04.txt
foo_05.txt
foo_06.txt
foo_07.txt
foo_08.txt
foo_09.txt
foo_10.txt
foo_11.txt
.........
.........
foo_100.txt
foo_101.txt

when i use

import glob
PATH = "C:\testfoo"
listing = glob.glob(os.path.join(PATH, '*.txt'))

i have this order

    foo_00.txt
    foo_01.txt
    foo_02.txt
    foo_03.txt
    foo_04.txt
    foo_05.txt
    foo_06.txt
    foo_07.txt
    foo_08.txt
    foo_09.txt
    foo_100.txt
    foo_101.txt
    .........
    .........
    foo_10.txt
    foo_11.txt
    .........

i tried also sorted(glob.glob(os.path.join(PATH, '*.txt'))) but without resolve my problem because I wish to have the right sequence. After foo_09.txt i wish to import foo_10.txt and not foo_100.txt and so on.


回答1:


You can use a special key function for your sort.

sorted(files, key=lambda name: int(name[4:-4]))

What this does is, it takes the filename, e.g. foo_100.txt, strips away the first 4 and last 4 characters, converts the rest to an int, and sorts by those values.

Of course, this only works if all the files have the same prefix and extension, and you may have to use different numbers for other file names. Alternatively, you can use the split method of string or a regular expression to extract the numeric part in the key function.



来源:https://stackoverflow.com/questions/19658008/ordered-with-glob-glob-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!