首页 > 解决方案 > 如何使用python对存储在列表中的文件夹项目进行升序?

问题描述

我有一个包含一些 xml 文件的文件夹。我正在尝试读取这些文件并将其按升序存储在列表中。我已经编写了以下代码,但是,我不知道该怎么做。该文件夹包含以下文件:

a.xml_1

a.xml_2

a.xml_3

...

当我运行以下代码时,创建的列表没有排序。

import os

path = 'mypath/folder/'

xml_files=[]
files = os.listdir(path)

for f in files:
    xml_files=[f]
    print(xml_files)

标签: python

解决方案


import os

print (sorted(os.listdir('./')))

你也可以使用glob顺便说一句:

import glob

print (sorted(glob.glob('./*')))

如果您希望对字母数字字符串进行排序,您可能会遇到麻烦。有一个著名的功能:

import re

def sorted_nicely( l ): 
    """ Sort the given iterable in the way that humans expect.""" 
    convert = lambda text: int(text) if text.isdigit() else text 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)

然后你可以使用:

 print (sorted_nicely(os.listdir('./')))

推荐阅读