在目录中查找文件名中编号最高的文件 [英] Find file in directory with the highest number in the filename

查看:167
本文介绍了在目录中查找文件名中编号最高的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与> Python识别文件作为文件名一部分的数字最大的

我想将文件附加到某个目录.文件的名称为:file1,file2 ...... file ^ n.如果我一次性完成此操作,但是当我想再次添加文件,并想查找最后添加的文件(在这种情况下,文件编号最高)时,它将识别出"file6"高于"file100" '.

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'.

我该如何解决.

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.

编辑,我的文件名在数字后具有扩展名".txt"

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

推荐答案

我将尝试仅使用文件名而不使用日期来解决它.

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

概念证明:

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))

结果:file100

  • key函数提取在文件末尾找到的数字并转换为整数,如果没有找到,则返回-1
  • 您不需要sort来找到最大值,只需将密钥直接传递给max
  • 如果2个文件具有相同的索引,请使用完整的文件名来打领带(这说明了tuple键)
  • 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)

这篇关于在目录中查找文件名中编号最高的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆