【问题标题】:Find file in directory with the highest number in the filename在文件名中编号最大的目录中查找文件
【发布时间】:2017-08-21 19:55:01
【问题描述】:

我的问题与Python identify file with largest number as part of filename密切相关

我想将文件附加到某个目录。文件的名称是:file1,file2......file^n。如果我一次性执行此操作,但当我想再次添加文件并想要查找添加的最后一个文件(在本例中为最高编号的文件)时,它会识别 'file6' 高于 'file100 '。

我该如何解决这个问题。

import glob
import os

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

如您所见,我尝试查看创建时间,也尝试查看修改时间,但它们可能相同,因此无济于事。

编辑我的文件名在数字后有扩展名“.txt”

【问题讨论】:

    标签: python blob filenames


    【解决方案1】:

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

    在应用标准或字母数字排序应用于整个文件名之前,您必须转换为整数

    概念证明:

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

    【讨论】:

    • 如果我们假设输入格式正确,那么简单地删除前四个字符可能会更容易。
    • 对不起,我的文件名的扩展名为“.txt”。因为你的代码不起作用,这是我的错误。我如何调整正则表达式以忽略这一点?
    • s = re.findall("(\d+).txt", f) 用于 .txt 文件扩展名
    【解决方案2】:

    使用下面的正则表达式可以得到每个文件的编号:

    import re
    
    maxn = 0
    for file in list_of_files:
        num = int(re.search('file(\d*)', file).group(1))  # assuming filename is "filexxx.txt"
        # compare num to previous max, e.g.
        maxn = num if num > maxn else maxn
    

    在循环结束时,maxn 将是您的最高文件名编号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 2021-01-12
      • 1970-01-01
      相关资源
      最近更新 更多