如何解决通过文件夹进行问题迭代并找到特定文件的时间戳
我写了一个函数 i Python,它遍历一个根文件夹,其中包含文件夹内的不同文件夹。
这些文件夹包含许多不同的文件,但我特别是只在过去 24 小时内创建的文件夹中查找 PNG 文件。
我写了这段代码,但不幸的是我得到了一个错误..
for root,dirs,files in os.walk(rootFolder):
# if(datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y") == "2021"):
for file in files:
if file.endswith(".png"):
time = datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y")
print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
显然,当我尝试打电话时:
print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
我收到“FileNotFoundError: [WinError 2] 文件未找到:'001-001-001.png'
当它在错误消息中将名称返回给我时,我不明白这个“未找到”部分???
如果我在函数中写入 root,我会得到一个结果并返回时间戳,但那些不是我需要的。
print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
我正在考虑这样做:
for root,files in os.walk(rootFolder):
# if(datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y") == "2021"):
for file in files:
if file.endswith(".png") and datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d") == datetime.now().strftime("%Y:%m:%d"):
time = datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y")
print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
我将 png 文件的时间戳与当前时间进行比较,并检查它们是否早于 24 小时/天。但不幸的是,由于代码无法将“文件”作为输入,我收到一个错误在 getmtime() 函数中..
希望有人能帮助我。
解决方法
脚本是否使用了预期的目录?
您可以使用以下命令检查目录:
print("current directory: ",os.getcwd())
print("root: ",root)
print("current file: ",file)
如果您从 PNG 文件夹运行,您的初始脚本应该可以工作。
或者您使用文件的完整路径,例如:
timestamp = os.path.getmtime(os.path.join(root,file))
print(datetime.fromtimestamp(timestamp).strftime("%Y:%m:%d"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。