1

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)
Sociopath
  • 13,068
  • 19
  • 47
  • 75
  • Do you want to sort them alphabetically and then display the last one? – Capie Feb 17 '20 at 11:47
  • 3
    Sorting alphabetically will give you for example, `filename1`, `filename10`, `filename2`... You need to sort according to the number **as a number**, not as string – Tomerikoo Feb 17 '20 at 11:50
  • Does this answer your question? [Getting the last element of a list](https://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list) – MSpiller Feb 17 '20 at 11:54
  • One problem is that "sorted" returns a new list. You can try "files.sort()" instead. – Michael Butscher Feb 17 '20 at 11:55

2 Answers2

5

you can use the built-in function max:

import re

last_file = max(files, key=lambda x: int(re.search(r'\d+', x).group()))
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

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

leportella
  • 43
  • 2
  • 10