微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决有没有办法在Python目录中查找特定的子文件夹?

我有一个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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。