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

2024-09-26 04:57:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

一号文件。。。。你知道吗

文件二。。。。你知道吗

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

我还想添加一个计数器,在最后将显示多少文件被删除。你知道吗

非常感谢!你知道吗


Tags: and文件thepath脚本datetimeosdir
2条回答

一般来说,通过定义函数将问题分解成碎片是很有帮助的。它使调试更容易,使代码更可读。你知道吗

#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来测试它_删除.py运行$python3自定义_删除.py你知道吗

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

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

相关问题 更多 >