有没有办法在 Python 的目录中找到特定的子文件夹?

Is there a way to find specific sub folders in a directory in Python?

我有一个 Python 程序,我在其中搜索一个目录,但对于该目录中的某些子文件夹,如果它们创建时间超过 7 天,我想删除其中的文件,其余的如果创建超过 21 天,目录中的文件将被删除。

因此在本地用户之后是公司文件夹,在该文件夹中是我需要的子文件夹,例如房屋、地址和 Phone 有什么建议吗?

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)

您可以先创建一个 white_listed 文件夹列表,然后像这样遍历其中的文件:

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, dirs, files in os.walk(folder_path):
        for file in files:
            print(file)
            #do something