首页 > 解决方案 > 查找最近编辑的文件的 Python 脚本(从前两天到现在编辑)

问题描述

我正在尝试编写一个 Python 脚本来查找计算机上所有最近编辑的文件。

下面是代码。

import os
import datetime as dt

now = dt.datetime.now()
ago = now-dt.timedelta(hours=48)

for root, dirs,files in os.walk('.'):
    for fname in files:
        path = os.path.join(root, fname)
        st = os.stat(path)
        mtime = dt.datetime.fromtimestamp(st.st_mtime)
        if mtime > ago:
            print('%s modified %s'%(path, mtime))

标签: pythonpython-3.x

解决方案


在 linux 上,mtime 返回为 UTC,而在 windows 上它是本地化的。此外,日期时间对象是愚蠢的(默认情况下不要担心时区),所以我们最好使用时间戳。

这是一个使用ofunctions.file_utils包来遍历路径的工作版本。ofunctions.file_utils也恰好有一个file_creation_date()功能;)

首先安装软件包

python -m pip install ofunctions.file_utils

然后使用以下脚本

import os
import datetime as dt

if os.name == 'nt':
    now = dt.datetime.now().timestamp()
else:
    now = dt.datetime.utcnow().timestamp()
ago = 86400 * 2  # Since we deal in timestamps, lets declare 2 days in seconds

files = get_files_recursive('.')
for file in files:
    mtime = os.stat(file).st_mtime
    if mtime > now - ago:
        print('%s modified %s'%(file, mtime))

免责声明:我是 ofunctions 的作者


推荐阅读