Python 3.x 删除Y文件夹中早于X天的每个文件
这是我写的,但不起作用。 在Python 3.x 删除Y文件夹中早于X天的每个文件,python-3.x,raspbian,raspberry-pi3,Python 3.x,Raspbian,Raspberry Pi3,这是我写的,但不起作用。 在giorni中,我将最长停留天数放在SD中,file_dir是分析文件的默认位置 import os from datetime import datetime, timedelta file_dir = "/home/pi/" #location giorni = 2 #n max of days giorni_pass = datetime.now() - timedelta(giorni) for root, dirs, files in os.walk
giorni
中,我将最长停留天数放在SD中,file_dir
是分析文件的默认位置
import os
from datetime import datetime, timedelta
file_dir = "/home/pi/" #location
giorni = 2 #n max of days
giorni_pass = datetime.now() - timedelta(giorni)
for root, dirs, files in os.walk(file_dir):
for file in files:
filetime = datetime.fromtimestamp(os.path.getctime(file))
if filetime > giorni_pass:
os.remove(file)
解决方法:
for file in files:
path = os.path.join(file_dir, file)
filetime = datetime.fromtimestamp(os.path.getctime(path))
if filetime > giorni_pass:
os.remove(path)
因为“Filenames”包含一个文件列表,其路径名与“file\u dir”相对,要对这些文件进行操作,应首先使用path=os.path.join(file\u dir,file)