4

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.

4

1 回答 1

17

您可以使用特殊key功能进行排序。

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

它的作用是,它采用文件名,例如foo_100.txt,去掉前 4 个和后 4 个字符,将其余字符转换为int,并按这些值排序。

当然,这仅适用于所有文件具有相同前缀和扩展名的情况,并且您可能必须为其他文件名使用不同的数字。或者,您可以使用split字符串或正则表达式的方法来提取键函数中的数字部分。

于 2013-10-29T12:28:30.677 回答