python - 查找最近编辑的文件的 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))
解决方案
在 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 的作者
推荐阅读
- sql - SQL中从上一年月到今年月的数字总和
- verilog - 语法错误,意外的“=”,需要 IDENTIFIER
- asp.net - 部署在 Ubuntu 上的 .NET Core 应用程序的语言环境问题
- c# - 无法注册后台任务
- sql-server - 使用 DTEXEC.EXE 命令行实用程序时如何获取 SSIS 包的实际执行时间
- python - 为什么我的循环没有在我设置的数字处停止?
- typescript - 如何避免打字稿中以相同单词结尾的命名空间冲突
- routes - 我可以从外部将 json 数据发送到秘银路由吗
- python - 具有不同节点集的两个 NetworkX 图之间的差异
- c - 在 C 中使用递归的斐波那契数列