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

时间:2018-02-08 09:46:46

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

以下代码运行良好,并为我提供了带文件路径的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

但是如果创建了文件,那么它将提供文件路径,但是如果创建了文件夹,那么它将给出文件夹路径。而我只期望文件而不是特定文件夹中创建的文件夹。

请注意,建议我应该只获取最新创建的文件路径,而不是最新创建的文件夹路径。

3 个答案:

答案 0 :(得分:2)

你可以使用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

答案 1 :(得分:1)

如果您已经导入操作系统,那么您不需要任何其他模块来实现此目的。 os有一个名为path的模块,它处理与路径相关的函数。

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

答案 2 :(得分:0)

试试这个:

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))
相关问题