首页 > 解决方案 > 如何从 Python 中的特定文件夹中获取最新文件

问题描述

我有两个扩展名为 .xlsb 和 .msg 的目录,即每月和每周。我想从每个文件夹中获取最新的文件。

我对两者都使用相同的代码,但我只收到每周文件夹的错误。

self.weekly_file = [os.path.join(self.weekly_path, x) for x in os.listdir(self.weekly_path) if
                          x.endswith(".xlsb")]
    
print(self.weekly_file)
self.newest_weekly_file = os.path.basename(max(self.weekly_file, key=os.path.getctime))
print(self.newest_weekly_file)

我收到错误消息:

return os.stat(filename).st_ctime
OSError: [WinError 1] Incorrect function: '\\\\docs.xyz.net.au\\sites\\K7777\\Reports\\Week\\Week - 2021-05-10.xlsb'

即使我尝试了下面的代码,这也只给出了文件夹名称。

self.weekly_file = glob.glob(self.weekly_path)

标签: pythonglobpython-os

解决方案


试试这个:

xlsb_weekly = glob.glob('self.weekly_path/*.xlsb')
newest_weekly_file = max(xlsb_weekly, key=os.path.getctime)
print(newest_weekly_file)

推荐阅读