如何删除Python中早于x天且未在周日创建的子目录中的所有文件



我想找到一个解决方案,删除子目录中所有早于x天的文件,如果文件是在周日创建的,则不应删除

我的主文件夹路径是C:\Main_Folder,在我拥有的结构中,

+---Sub_Folder_1
|       Day1.xlsx
|       Day2.xlsx
|       Day3.xlsx
|
+---Sub_Folder_2
|       Day1.xlsx
|       Day2.xlsx
|       Day3.xlsx
|
---Sub_Folder_3
Day1.xlsx
Day2.xlsx
Day3.xlsx

我尝试了下面的代码,但它甚至删除了子目录以及

import os, shutil
folder = 'C:\Main_Folder\'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)

为了检查上次编辑文件的时间,需要包含两个库。import os.path, time

首先要考虑的是要从文件中使用哪个字段,例如:

print("Last Modified: %s" % time.ctime(os.path.getmtime("file.txt")))
# Last Modified: Mon Jul 30 11:10:21 2018
print("Created: %s" % time.ctime(os.path.getctime('file.txt')))
# Created: Tue Jul 31 09:13:23 2018

因此,您必须解析这一行,并查找要考虑早于x日期的字段。考虑在Sun, Mon, Tue, Wed, Thur, Fri, Sat的字符串中查找周值。

fileDate = time.ctime(os.path.getmtime('file.txt'))
if 'Sun' not in fileDate:
# Sun for Sunday is not in the time string so check the date and time

您必须循环浏览子目录中的文件,检查"创建时间"或"上次修改时间",然后从字符串中解析日期和时间字段,并与您的情况进行比较,删除那些您认为适合删除的字段。

最新更新