如何获取目录中最大文件名python的文件名?

How to get the filename in directory with the max number in the filename python?

我在文件夹中有一些 xml 文件,例如 'assests/2020/2010.xml''assests/2020/20005.xml''assests/2020/20999.xml' 等。我想在 ' 2020'文件夹。对于以上三个文件,输出应该是 20999.xml

我正在尝试如下:


import glob
import os

list_of_files = glob.glob('assets/2020/*')
# latest_file = max(list_of_files, key=os.path.getctime)
# print (latest_file)

我无法找到获取所需文件的逻辑。 是对我的查询有最佳答案的资源,但我无法建立我的逻辑。

我现在无法测试,但你可以试试这个:

files = []
for filename in list_of_files:
    filename = str(filename)
    filename = filename.replace('.xml','') #Assuming it's not printing your complete directory path
    filename = int(filename)
    files += [filename]

print(files)

这应该会为您提供整数格式的文件名,现在您应该能够按降序对它们进行排序并获得排序列表的第一项。

使用 re 在您的文件路径中搜索适当的结尾。如果找到,请再次使用 re 来提取 nr。

import re

list_of_files = [
    'assests/2020/2010.xml',
    'assests/2020/20005.xml',
    'assests/2020/20999.xml'
    ]

highest_nr = -1
highest_nr_file = ''
for f in list_of_files:
    re_result = re.findall(r'\d+\.xml$', f)
    if re_result:
        nr = int(re.findall(r'\d+', re_result[0])[0])
        if nr > highest_nr:
            highest_nr = nr
            highest_nr_file = f

print(highest_nr_file)

结果

assests/2020/20999.xml 
import glob

xmlFiles = [] 
# this will store all the xml files in your directory
for file in glob.glob("*.xml"):
    xmlFiles.append(file[:4])

# this will print the maximum one
print(max(xmlFiles))

你也可以这样试试

import os, re

path = "assests/2020/"

files =[
"assests/2020/2010.xml",
"assests/2020/20005.xml",
"assests/2020/20999.xml"
]

n = [int(re.findall(r'\d+\.xml$',file)[0].split('.')[0]) for file in files]


output = str(max(n))+".xml"
print("Biggest max file name of .xml file is ",os.path.join(path,output))

输出:

Biggest max file name of .xml file is  assests/2020/20999.xml

您可以使用 pathlib 对 xml 文件进行 glob,并访问路径对象属性,如 .name 和 .stem:

from pathlib import Path

list_of_files = Path('assets/2020/').glob('*.xml')
print(max((Path(fn).name for fn in list_of_files), key=lambda fn: int(Path(fn).stem)))

输出:

20999.xml