繁体   English   中英

如何使用python获取最新创建的文件名而不是文件夹名?

[英]How to get the latest created file name and not the folder name using python?

以下代码运行良好,并为我提供了带有文件路径的require输出。

import glob
import os

list_of_files = glob.glob('/path/to/folder/*')
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

但是,如果创建了文件,则将提供文件路径,但是如果创建了文件夹,则将提供文件夹路径。 而我只希望文件而不是在特定文件夹中创建的文件夹。

请建议我该怎么做以仅获取最新创建的文件路径而不获取最新创建的文件夹路径。

您可以使用lambdas使用类似这样的东西

filelist = os.listdir(os.getcwd())
filelist = filter(lambda x: not os.path.isdir(x), filelist)
newest = max(filelist, key=lambda x: os.stat(x).st_mtime)

完整答案发布在这里https://ubuntuforums.org/showthread.php?t=1526010

如果您已经导入了os,则不需要任何其他模块即可实现。 os有一个称为path的模块,用于处理与路径相关的功能。

要检查路径是目录还是文件,可以检查os.path.isfile('/path/here') ,这将返回布尔值truefalse具体取决于传递的参数是文件还是文件。

尝试这个:

import glob
import os

def check_file_status(path,direc=None):
    if direc==None:
        list_of_files = glob.glob(path)
        latest_file = max(list_of_files, key=os.path.getctime)
        return latest_file
    else:
        new_path = direc+'/*'
        list_of_files = glob.glob(new_path)
        latest_file = max(list_of_files, key=os.path.getctime)
        return latest_file

if __name__ =="__main__":

    path = '/your path to file/*'
    if os.path.isfile(check_file_status(path)):
            print(latest_file)

    elif os.path.isdir(check_file_status(path)):
            add_into_path = check_file_status(path)
            print(check_file_status(path,add_into_path))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM