python - 如何使用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)
解决方案
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('./')))
推荐阅读
- r - 为什么 fread() 花了这么长时间?(R 4.0.3)
- typescript - 如何限制打字稿的文字表达式只接受可用的属性?
- android - 致命异常:主进程:com.delegates.predelegatesapprider,PID:8258 java.lang.NoClassDefFoundError:
- android - 自定义背景资源在android中不起作用
- ios - swift如何让UILabel对齐到左上角
- reactjs - 我无法为元标记分配动态值?
- javascript - JQuery.Ajax() 不工作不确定脚本是否正确加载
- assembly - 是否可以在基于累加器的机器/ISA 中实现流水线操作?
- azure-active-directory - 免费 Office 帐户的无效授权错误
- python - 大熊猫汇总