如何在文件夹中搜索特定日期和时间修改的CSV文件?

2024-06-24 13:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Python在共享目录中自动搜索在特定日期和时间修改的文件

手动步骤目前如下所示:

*check file created with Previous business date in \\fcganas3\FICC\FIC_CMT\SecurityAnalytics\
or \\fcganas3\FICC\FIC_CMT\SecurityAnalytics\Load\ folder*
Filename: " BBG-BIGE-SPFD_1_YYYYMMDD.csv "  (YYYYMMDD - Previous Working Day).

我能够在本地目录中搜索文件(请参阅下面的代码)

    import os
    import glob
    
    path = 'e:\\'
    extension = 'pdf'
    os.chdir(path)
    result = glob.glob('*.{}'.format(extension))
    print(result)

Tags: 文件pathimport目录osextensionresultglob
2条回答

当您转到该文件夹并使用gl0b.glob时,您将获得该文件夹中的文件列表。循环遍历文件名,提取最后8个字符,并将其与所需日期匹配

您正在查找datetime和timedelta

我在下面用例子扩展了你的代码来回答你的问题

import os
import glob
import os.path, time
from datetime import datetime, timedelta

path = 'e:\\'
extension = 'csv' # You asked for csv but your example had pdf...
os.chdir(path)
result = glob.glob('*.{}'.format(extension))

for fil in result:
    last_mod = datetime.fromtimestamp(os.path.getmtime(fil))
    print("last modified: %s" % last_mod)
    specific_day_and_time = datetime.strptime('2020-08-07 09:00:00', '%Y-%m-%d %H:%M:%S')
    print("Since specific time: {}".format(specific_day_and_time - last_mod))
    yesterday = datetime.now() - timedelta(days=1)
    if yesterday - last_mod  > timedelta(days=1):
        print("It's been more than a day since this file was updated")

相关问题 更多 >