Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Find file in directory with the highest number in the filename

My question is closely related to Python identify file with largest number as part of filename

I want to append files to a certain directory. The name of the files are: file1, file2......file^n. This works if i do it in one go, but when i want to add files again, and want to find the last file added (in this case the file with the highest number), it recognises 'file6' to be higher than 'file100'.

How can i solve this.

import glob
import os

latest_file = max(sorted(list_of_files, key=os.path.getctime))
print latest_file

As you can see i tried looking at created time and i also tried looking at modified time, but these can be the same so that doesn't help.

EDIT my filenames have the extention ".txt" after the number

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll try to solve it only using filenames, not dates.

You have to convert to integer before appling criteria or alphanum sort applies to the whole filename

Proof of concept:

import re
list_of_files = ["file1","file100","file4","file7"]

def extract_number(f):
    s = re.findall("d+$",f)
    return (int(s[0]) if s else -1,f)

print(max(list_of_files,key=extract_number))

result: file100

  • the key function extracts the digits found at the end of the file and converts to integer, and if nothing is found returns -1
  • you don't need to sort to find the max, just pass the key to max directly
  • if 2 files have the same index, use full filename to break tie (which explains the tuple key)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...