Python新手。我试图写一个脚本,将删除文件,是超过60天。我知道有很多现成的例子,但我正在努力解决我自己。这是我的密码:
import os
from datetime import datetime
# Gets the current date and time.
dt1 = datetime.now()
dt = datetime.timestamp(dt1)
print(f"\nDate and time right now:\n{dt}")
# Changes the path.
cwd = os.getcwd()
print(f"\nCurrent path:\n{cwd}")
the_dir = "C:\\Users\\Downloads\\Test"
change_dir = os.chdir(the_dir)
cwd = os.getcwd()
print(f"\nChanged the path to:\n{cwd}\n")
# All the files in directory/path
list_dir = os.listdir(cwd)
#print(list_dir)
count = 0
#Checks when the files were modified the lastest and removes them.
for files in list_dir:
#count = 0+1
last_modi =os.path.getctime(files)
dt_obj = datetime.fromtimestamp(last_modi)
print(last_modi)
# 5184000 = 60 days
if (dt-last_modi) >= 5184000:
print(files)
print("This file has not been modified for 60 days.")
os.unlink(files)
print(f"{files} removed.")
我要你们帮我看看我错过了什么。在我的文件夹/目录中有四个文件。其中三个已超过6个月,其中一个文件是新创建的。当我在if语句中打印文件时,它会显示所有文件,当我运行脚本时,不会删除任何文件。你知道吗
我想添加到脚本中的一些附加内容是打印一个列表,其中显示: 这些文件将被删除:
一号文件。。。。你知道吗
文件二。。。。你知道吗
确实要删除它们吗?(是或否)
我还想添加一个计数器,在最后将显示多少文件被删除。你知道吗
非常感谢!你知道吗
一般来说,通过定义函数将问题分解成碎片是很有帮助的。它使调试更容易,使代码更可读。你知道吗
您可以通过终端将脚本保存为custom来测试它_删除.py运行$python3自定义_删除.py你知道吗
您应该将所有文件路径存储在一个列表中,然后检查输入以继续删除或不删除。你知道吗
相关问题 更多 >
编程相关推荐