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



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

这就是我所拥有的:

import os
import datetime
import glob
path = r'C:UsersuserDesktopTEST FILES TO DELETE'
logging_path = r'C:UsersuserDesktopDelete 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 agon')
os.remove(os.path.join(root, name))

这就是我尝试做的:

import os
import datetime
import glob
path = [r'C:UsersuserDesktopTEST FILES TO DELETE', r'C:UsersuserDesktopTEST FILES TO DELETE3']
logging_path = r'C:UsersuserDesktopDelete 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 agon')
os.remove(os.path.join(root, name))

在尝试了这个之后,我在第15行得到了一个关于chdir的错误。我显然错过了一些东西,但我对Python或编程的了解还不够。

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

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

注意,你需要更新每个路径到p.

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

最新更新