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

时间:2019-10-07 08:52:49

标签: python python-3.x

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 ....

提交两个文件。...

确定要删除它们吗? (是或否)

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

非常感谢您!

2 个答案:

答案 0 :(得分:0)

您应将所有文件路径存储在一个列表中,然后检查输入内容是否继续删除。

VarsWithInfo[ruleVar]

答案 1 :(得分:0)

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

#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并运行$ python3 custom_delete.py来通过终端对其进行测试