I have same file name eg: filename1, filename2 , filename3, filename4 ..... filename10
I want to find last file of that specific name over here last file name is 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
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.