如何对文件夹进行升序';是用python存储在列表中的项目吗?
我有一个包含一些xml文件的文件夹。我正在尝试读取这些文件,并将其按升序存储在列表中。我已经写了以下代码,但是,我不知道怎么做。该文件夹包含以下文件: a、 xml_1 a、 xml_2 a、 xml_3 当我运行以下代码时,创建的列表没有排序如何对文件夹进行升序';是用python存储在列表中的项目吗?,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_fil
import os
path = 'mypath/folder/'
xml_files=[]
files = os.listdir(path)
for f in files:
xml_files=[f]
print(xml_files)
您也可以使用glob
btw:
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('./')))
试试这个,它会将所有文件按升序排列在一个列表中
import os
path = 'mypath/folder/'
xml_files=[]
files = os.listdir(path)
for f in files:
xml_files.append(f)
xml_files.sort()
print(xml_files)
好。你还没有试着点过,那你为什么会期望它呢?调查分类,谢谢。然而,当我这样排序时,在
xml\u 1
之后,它给出xml\u 10
,然后转到xml\u 11
所以,xml\u 2
发生在xml\u 19
之后,谢谢。然而,当我这样排序时,在xml\u 1
之后,它给出xml\u 10
,然后转到xml\u 11
。另外,xml\u 2
发生在xml\u 19
之后。为此,您需要使用我建议的sorted\u函数。
import os
path = 'mypath/folder/'
xml_files=[]
files = os.listdir(path)
for f in files:
xml_files.append(f)
xml_files.sort()
print(xml_files)