0

我正在尝试返回在创建的日期范围内的文件路径列表。我对 Python 比较陌生,几乎只在 ArcMap 中使用它,所以我有点困惑。我也无权访问某些看起来可以在我的工作计算机上对此有所帮助的模块。

在此页面的帮助下,我已经列出了文件夹中的所有文件路径,并按创建日期对它们进行了排序。


import os, stat, time

path = r"\\my\ImageData"
 
filepaths = [os.path.join(path, file) for file in os.listdir(path)]

print(filepaths)
 
files_sorted_by_date = []

file_statuses = [(os.stat(filepath), filepath) for filepath in filepaths]

files = ((status[stat.ST_CTIME], filepath) for status, filepath in file_statuses if stat.S_ISREG(status[stat.ST_MODE]))


for creation_time, filepath in sorted(files):
    creation_date = time.ctime(creation_time)
    files_sorted_by_date.append(creation_date + " " + filepath)

print(files_sorted_by_date)

采取哪些步骤仅列出我提供的日期范围内的“创建日期”的文件路径?

此外,我的文件路径以双倍 \ 字符(开头 4 个,每个文件夹之间 2 个)列出,因此不能直接粘贴到 Windows 资源管理器中以查找我的文件。它们最终将充当超链接,因此它们需要是正确的。我可以进行查找和替换以将 \ \ 更改为 \ 但我想知道我是否从一开始就做错了什么导致这种情况发生。

编辑:

我正在尝试使用 os.walk() 搜索目录中子文件夹中的所有文件。

import os, stat, time
from datetime import datetime

path = r"\\my\imagefolder"

filepaths = []

for subdir, dirs, files in os.walk(path):
    for file in files:
        filepath = os.path.join(subdir, file)
        filepaths.append(filepath)
        
print(filepaths)

#above is my attempt to search within subfolders, below is code I used from @Deo's comment

#datetime(year, month, day, hour, minute, second, microsecond)
range_start = datetime.date(datetime(2020, 3, 19))   #19th March 2020 to..
range_end = datetime.date(datetime(2021, 4, 19))    #19th April 2021

#get path only if its a file
filepaths = [os.path.join(path, file) for file in os.listdir(path) if os.path.isfile(file)]

#filter again if creation time is between the above range
filepaths = [paths for paths in filepaths if os.path.getctime(paths) > range_start and os.path.getctime(paths) < range_end]

print("\n".join(sorted(filepaths)))

print(filepaths)

在我的 for 循环之后使用 os.walk() 的文件路径列表的第一个打印语句返回路径中每个子文件夹中的每个文件路径。代码末尾的倒数第二个不返回任何内容,最后一个返回一个空列表。我认为我处理文件路径列表的两种方式是不兼容的,在某些时候列表被清空了。

如果我删除“仅当它是文件时获取路径”行,它会返回错误 TypeError: can't compare datetime.date to float。

我已确认此日期范围内确实存在文件。

4

1 回答 1

0
import os, stat, time
from datetime import datetime

path = "\\my\\ImageData"

#datetime(year, month, day, hour, minute, second, microsecond)
range_start = datetime.timestamp(datetime(2020, 7, 1, 23, 55, 59, 0))   #1st Jul 2020 11:55:59PM to..
range_end = datetime.timestamp(datetime(2021, 8, 10, 23, 55, 59, 0))    #10th Aug 2021 11:55:59PM

#get path only if its a file
filepaths = [os.path.join(path, file) for file in os.listdir(path) if os.path.isfile(file)]

#filter again if creation time is between the above range
filepaths = [paths for paths in filepaths if os.path.getctime(paths) > range_start and os.path.getctime(paths) < range_end]

print("\n".join(sorted(filepaths)))
于 2021-07-28T04:07:13.453 回答