如何仅在2012年之后在os路径python中添加条件以列出文件

问题描述

我有下面的代码,其中列出了文件夹和子文件夹中的所有文件。我想添加仅列出在2012年之后修改的文件的代码

path=r'c:\xx\download'
files_sorted_by_date = []
filenm=[]
filept=[]
creation=[]
filepaths=[]
for root,dirs,files in os.walk(path):
    for file in files:
        filepaths.append(os.path.join(root,file))

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

files = ((status[stat.ST_MTIME],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)
    filename = os.path.basename(filepath)
    filept.append(filepath)
    filenm.append(filename)
    creation.append(creation_date)
    files_sorted_by_date.append(creation_date + "," + filename)

    #print(files_sorted_by_date)

df =pd.DataFrame(files_sorted_by_date,columns=['files'])

解决方法

您可以使用os.path.getmtime(path)来获取自1970年以来的秒数

您可以使用time.localtime(os.path.getmtime(path))将其转换为元组

输出将是这样的(2006,8,17,12,6,3,229,1)

现在您可以获取元组的第一个值(年份)。

year = time.localtime(os.path.getmtime(path))[0]

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...