[英]How to do an ascending order of a folder's items stored in a list with 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('./*')))
如果您希望對字母數字字符串進行排序,您可能會遇到麻煩。 有一個著名的 function :
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.