问题描述
我有一个Python程序,我正在其中搜索目录,但是如果该目录中的某些子文件夹创建时间超过7天,并且要删除其中的某些子文件夹,则我想删除其中的文件如果创建时间超过21天。
因此,在本地用户之后是公司文件夹,而在该文件夹内是我需要的子文件夹,例如房屋,地址和电话吗?
import os
from datetime import date,timedelta,datetime
import time
#Path for the employee files
path ="C:/inetpub/ftproot/LocalUser/"
#Function to delete the files
def deleteFiles(days,path):
#Set time Value (86400 secs in 24 hours)
current_time = time.time()
time_in_secs = current_time - (days * 86400)
# Check to see if the path exists
if os.path.exists(path):
for root,dirs,files in os.walk(path):
for file in files:
full_path = os.path.join(root,file)
file_status = os.stat(full_path)
#print( full_path)
if(current_time - file_status.st_mtime) // (86400) >= days:
print(full_path)
#os.remove(full_path)
#print(full_path + "\nhas been deleted")
else:
print("Error Path Doesn't Exist!!!!!!!!!!!!")
deleteFiles(7,path)
解决方法
您可以先创建一个列入白名单的文件夹的列表,然后像这样遍历它们中的文件:
import os
from datetime import date,timedelta,datetime
import time
path = r"C:/inetpub/ftproot/LocalUser/"
white_list = ["House","Address"]
lst_white_folder = []
if os.path.exists(path):
for root,dirs,files in os.walk(path):
if os.path.split(root)[-1] in white_list:
# print(os.path.split(root)[-1])
lst_white_folder.append(root)
# alternatively you could provide the listof folderpaths directly of course
for folder_path in lst_white_folder:
for root,files in os.walk(folder_path):
for file in files:
print(file)
#do something