【问题标题】:How to list file names in order using python [duplicate]如何使用python按顺序列出文件名[重复]
【发布时间】:2021-09-01 01:31:04
【问题描述】:

我正在从一个目录中获取所有文件名列表 但是当我排序时,它不是根据final.txt 文件中的数字文件名排序的

我的 Python 代码:

pth=r'/d/demo'
fname=glob.glob(pth+"/['ABC']*.txt")
nlist='/d/bk/final.txt'

fname.sort()

for i in fname:
    file=os.path.basename(i)
    nlist.write(file+os.linesep)

以上代码输出格式如下 final.txt 文件

ABC1.txt
ABC11.txt
ABC10.txt
ABC2.txt
ABC3.txt
ABC4.txt
ABC5.txt
ABC6.txt
ABC7.txt
ABC8.txt
ABC9.txt
ABC13.txt
ABC12.txt

以下格式的预期输出:

ABC1.txt
ABC2.txt
ABC3.txt
ABC4.txt
ABC5.txt
ABC6.txt
ABC7.txt
ABC8.txt
ABC9.txt
ABC10.txt
ABC11.txt
ABC12.txt
ABC13.txt

【问题讨论】:

    标签: python


    【解决方案1】:

    你想要的是natural sort order。如果在您的情况下可以使用外部模块,那么您可以通过以下方式利用natsort(可能只是通过pip install natsort 安装):

    import natsort
    fname = ["ABC1.txt","ABC11.txt","ABC10.txt","ABC2.txt","ABC3.txt"]
    fname = natsort.natsorted(fname)
    print(fname)
    

    输出

    ['ABC1.txt', 'ABC2.txt', 'ABC3.txt', 'ABC10.txt', 'ABC11.txt']
    

    请注意,natsort.natsorted 应该像 sorted 一样使用,而不是 .sort,即它确实返回新的 list

    【讨论】:

    • 除 natsort 之外的任何其他方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2016-10-14
    • 2018-05-05
    相关资源
    最近更新 更多