简体   繁体   English

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

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

The following code works well and gives me the require output with the file path. 以下代码运行良好,并为我提供了带有文件路径的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

But if the file is created then it will give the file path but if the folder is created then it will give the folder path. 但是,如果创建了文件,则将提供文件路径,但是如果创建了文件夹,则将提供文件夹路径。 Whereas I was expecting only the file and not the folder created in a specific folder. 而我只希望文件而不是在特定文件夹中创建的文件夹。

Kindly, suggest what I should do to get only the latest created file path and not the latest created folder path. 请建议我该怎么做以仅获取最新创建的文件路径而不获取最新创建的文件夹路径。

you can use something like this using lambdas 您可以使用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)

The complete answer is posted here https://ubuntuforums.org/showthread.php?t=1526010 完整答案发布在这里https://ubuntuforums.org/showthread.php?t=1526010

If you are importing os already, then you don't need any other modules to achieve this. 如果您已经导入了os,则不需要任何其他模块即可实现。 os has a module called path which handles path related functions. os有一个称为path的模块,用于处理与路径相关的功能。

To check if a path is directory or a file, you can check os.path.isfile('/path/here') which will return a boolean true or false depending on if the passed parameter is a file or not 要检查路径是目录还是文件,可以检查os.path.isfile('/path/here') ,这将返回布尔值truefalse具体取决于传递的参数是文件还是文件。

Try this: 尝试这个:

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