如何从Python中的多个路径删除文件?

How to delete files from multiple paths in Python?

我正在学习有关创建 Python 脚本以删除超过特定天数的文件的教程。我能够成功地创建脚本并让它做我想做的事,但现在我需要它来扫描多条路径,而不仅仅是一条路径。我该怎么做?

这是我的:

import os
import datetime
import glob

path = r'C:\Users\user\Desktop\TEST FILES TO DELETE'
logging_path = r'C:\Users\user\Desktop\Delete Logs'

# Create log directory, wills skip if exists
if not os.path.isdir(logging_path):
    os.mkdir(logging_path)
else:
    print ("Directory already exists")

today = datetime.datetime.today() # Get current time
os.chdir(path) # Changing path to current path

# Create log file with timestamp
file=open(logging_path+datetime.datetime.today().strftime('%d-%m-%Y')+'.txt','a')

for root, directories, files in os.walk(path, topdown=False):
    for name in files:
        # Check last modified time
        t = os.stat(os.path.join(root, name))[8]
        filetime = datetime.datetime.fromtimestamp(t) - today

        # Is file older than 3 days?, If yes, delete.
        if filetime.days <= -3:
            print(os.path.join(root, name), filetime.days)
            file.write(os.path.join(root, name)+' created '+str(-1*filetime.days)+' days ago\n')
            os.remove(os.path.join(root, name))

这是我尝试做的:

import os
import datetime
import glob

path = [r'C:\Users\user\Desktop\TEST FILES TO DELETE', r'C:\Users\user\Desktop\TEST FILES TO DELETE3']
logging_path = r'C:\Users\user\Desktop\Delete Logs'

# Create log directory, wills skip if exists
if not os.path.isdir(logging_path):
    os.mkdir(logging_path)
else:
    print ("Directory already exists")

today = datetime.datetime.today() # Get current time
os.chdir(path) # Changing path to current path

# Create log file with timestamp
file=open(logging_path+datetime.datetime.today().strftime('%d-%m-%Y')+'.txt','a')

for root, directories, files in os.walk(path, topdown=False):
    for name in files:
        # Check last modified time
        t = os.stat(os.path.join(root, name))[8]
        filetime = datetime.datetime.fromtimestamp(t) - today

        # Is file older than 3 days?, If yes, delete.
        if filetime.days <= -3:
            print(os.path.join(root, name), filetime.days)
            file.write(os.path.join(root, name)+' created '+str(-1*filetime.days)+' days ago\n')
            os.remove(os.path.join(root, name))

虽然我在第 15 行收到有关 chdir 的错误,但在尝试此操作后。我显然遗漏了一些东西,但我对 Python 或编程的了解还不够多,无法解决这个问题。

您的 path 变量是一个路径数组,因此将其重命名为 paths,您需要在 os.chdiros.walk 中索引该数组,或者将路径变量更改为一个特定路径的字符串。

正如 Giacomo Catenazzi alredy 所解释的,您更改了路径的数据类型(从字符串到列表,这与 chdir 不兼容)。所以你需要像这样浏览列表中的每个成员:

for p in path:
    os.chdir(p)
    # the rest of your code

请注意,您需要更新 p 的每个路径。