代码帮助:删除超过 60 天的文件



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 语句中打印文件时,它会显示所有文件,当我运行脚本时,不会删除任何文件。

我想添加到脚本中的一些其他内容是我打印一个列表,其中显示: 这些是将被删除的文件:

file_one....

文件二....

您确定要删除它们吗?(Y 或 N(

我还想添加一个计数器,最终将显示删除了多少文件。

非常感谢!

您应该将所有文件路径存储在列表中,然后检查输入以继续删除或不删除。

now = datetime.now()
files_to_delete = []
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 (now - dt_obj).day >= 60:
print(files)
files_to_delete.append(files)
#print("This file has not been modified for 60 days.")
#os.unlink(files)
#print(f"{files} removed.")
if files_to_delete:
print("These are the files which will be deleted:n")
print(*files_to_delete, sep='n')
decision = input("Are you sure you want to delete them? (Y or N)")
if decision.upper() == 'Y':
for file in files_to_delete:
os.remove(file)
print(f"{file} removed.") 

通常,通过定义函数将问题分解为碎片是有帮助的。它使调试变得更加容易,并使代码更具可读性。

#custom_delete.py
#/usr/bin/python3
import os
import shutil
import platform
import time
import datetime
count = 0                      #initiating counter variable
ts = time.time()               #getting current time
cur_dir = "/home/foo/Desktop/" #change according to your needs
'''
This function returns the absolute path of the file and its last edit timestamp.
'''
def getLastEdit(file):         
mod_time = os.stat(cur_dir + file).st_mtime
abs_path = cur_dir + file
return abs_path, mod_time

'''
This function prompts a dialog and removes the file if accepted. 
Notice that its looking for files older than an hour, 
hence "3600". You can edit this function to batch remove. 
'''
def removeIfOld(abs_path, mod_time):
try:
if mod_time + 3600 < ts:
user_validation = input("Remove file:" + abs_path + "?" + ("Y/N"))
if user_validation.upper() == "Y":
os.remove(abs_path)
count += 1
if count % 10 == 0:
print("Deleted count:" + str(count))
except Exception as e:
print(e)
'''
Define our main process so script can run.
'''
if __name__ == "__main__":
for file in os.listdir(cur_dir):
removeIfOld(getLastEdit(file))

您可以通过终端进行测试,方法是将脚本另存为custom_delete.py并运行 $python 3 custom_delete.py

最新更新