如何使用python获取文件夹中的最新文件

时间:2016-09-05 08:58:24

标签: python python-3.x python-2.7

我需要使用python获取文件夹的最新文件。使用代码时:

max(files, key = os.path.getctime)

我收到以下错误:

  

FileNotFoundError:[WinError 2]系统找不到指定的文件:'a'

9 个答案:

答案 0 :(得分:189)

分配给files变量的内容不正确。使用以下代码。

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

答案 1 :(得分:24)

max(files, key = os.path.getctime)

代码非常不完整。什么是files?它可能是一个文件名列表,来自os.listdir()

但是这个列表只列出文件名部分(a.k.a。" basenames"),因为它们的路径很常见。为了正确使用它,你必须将它与通向它的路径相结合(并用于获取它)。

如(未经测试):

def newest(path):
    files = os.listdir(path)
    paths = [os.path.join(path, basename) for basename in files]
    return max(paths, key=os.path.getctime)

答案 2 :(得分:7)

我缺乏发表评论的声誉,但是Marlon Abeykoons回应的ctime并没有为我提供正确的结果。使用mtime可以解决问题。 (key = os.path.get m 时间))

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getmtime)
print latest_file

针对该问题,我找到了两个答案:

python os.path.getctime max does not return latest Difference between python - getmtime() and getctime() in unix system

答案 3 :(得分:4)

尝试按创建时间对项目进行排序。下面的示例对文件夹中的文件进行排序,并获取最新的第一个元素。

import glob
import os

files_path = os.path.join(folder, '*')
files = sorted(
    glob.iglob(files_path), key=os.path.getctime, reverse=True) 
print files[0]

答案 4 :(得分:3)

我建议使用glob.iglob()代替glob.glob(),因为它效率更高。

  

glob.iglob()返回一个迭代器,它产生与glob()相同的值,而不是实际同时存储它们。

这意味着glob.iglob()会更有效率。

我主要使用下面的代码来查找与我的模式匹配的最新文件:

LatestFile = max(glob.iglob(fileNamePattern),key=os.path.getctime)

注意: 有max函数的变体,如果找到最新文件,我们将使用以下变体: max(iterable, *[, key, default])

需要迭代,因此您的第一个参数应该是可迭代的。 如果找到最大值的nums,我们可以使用beow变体:max (num1, num2, num3, *args[, key])

答案 5 :(得分:0)

(编辑以改善答案)

首先定义一个函数get_latest_file

def get_latest_file(path, *paths):
    fullpath = os.path.join(path, paths)
    ...
get_latest_file('example', 'files','randomtext011.*.txt')

您也可以使用docstring!

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file 
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)

如果您使用Python 3 ,则可以使用iglob代替。

完整代码以返回最新文件的名称:

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file 
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)
    files = glob.glob(fullpath)  # You may use iglob in Python3
    if not files:                # I prefer using the negation
        return None                      # because it behaves like a shortcut
    latest_file = max(files, key=os.path.getctime)
    _, filename = os.path.split(latest_file)
    return filename

答案 6 :(得分:0)

我已经尝试使用上述建议而我的程序崩溃了,而不是我想出了我尝试识别的文件被使用以及尝试使用' os.path.getctime'它崩溃了。 最终对我有用的是:

    files_before = glob.glob(os.path.join(my_path,'*'))
    **code where new file is created**
    new_file = set(files_before).symmetric_difference(set(glob.glob(os.path.join(my_path,'*'))))

此代码获取两组文件列表之间的不常见对象 它不是最优雅的,如果同时创建多个文件,它可能不会稳定

答案 7 :(得分:0)

我一直在Python 3中使用它,包括文件名上的模式匹配。

from pathlib import Path

def latest_file(path: Path, pattern: str = "*"):
    files = path.glob(pattern)
    return max(files, key=lambda x: x.stat().st_ctime)

答案 8 :(得分:-1)

Windows上一个更快的方法(0.05s),调用一个执行此操作的bat脚本:

get_latest.bat

@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%

其中\\directory\in\question是您要调查的目录。

get_latest.py

from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)

如果找到文件stdout是路径,stderr是无。

使用stdout.decode("utf-8").rstrip()获取文件名的可用字符串表示。

相关问题