简体   繁体   English

在python中查找最后一个文件名

[英]Find the last file name in python

I have same file name eg: filename1, filename2 , filename3, filename4 ..... filename10我有相同的文件名,例如: filename1, filename2 , filename3, filename4 ..... filename10

I want to find last file of that specific name over here last file name is filename10我想在这里找到该特定名称的最后一个文件,最后一个文件名是 filename10

import os
import datetime
import re

files = []
for file in os.listdir("C:\\Users\\Mayur Pawar\\Desktop\\FTP work"):
    if file.endswith(".csv"):
        files.append(file)
#s = sorted(files)

#print(files)

sorted(files)

you can use the built-in function max :您可以使用内置函数max

import re

last_file = max(files, key=lambda x: int(re.search(r'\d+', x).group()))

You can use a Regex to do this.您可以使用正则表达式来执行此操作。 Not the most beautiful code ever, but it works.不是有史以来最漂亮的代码,但它有效。 However, if filename has other number, you may need a more complex regex:但是,如果文件名有其他数字,您可能需要更复杂的正则表达式:

import re

files = ["filename10", "filename2", "fileename3"]

highest = 0
filename = ""
for f in files:
    dd = re.search(r'\d+', f)
    filenumber = int(dd.group())
    if filenumber > highest:
        highest = filenumber
        filename = f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM