我正在尝试创建一个可浏览目录的脚本,如果该脚本被称为垃圾桶且早于3个月,则可以将其删除。
到目前为止,我已经有了这段代码。
import os, sys, time
from subprocess import call
import path
now = time.time()
cutoff = now - (30)#(91 * 86400)
path = '/users/shoot_station_5/documents/folderfordeletetest/'
for root, d_names, f_names in os.walk(path):
print (root, d_names, f_names)
for _dir in d_names:
if time.ctime(os.path.getmtime(_dir)) < cutoff:
print (_dir)
当我打印(root,d_names,f_names)时,它给我这个结果
/users/shoot_station_5/documents/folderfordeletetest/ ['dont_delete', 'dont_delete_me'] ['.DS_Store']
/users/shoot_station_5/documents/folderfordeletetest/dont_delete ['trash'] ['.DS_Store']
/users/shoot_station_5/documents/folderfordeletetest/dont_delete/trash [] []
/users/shoot_station_5/documents/folderfordeletetest/dont_delete_me ['trash'] ['.DS_Store']
/users/shoot_station_5/documents/folderfordeletetest/dont_delete_me/trash [] []
运行最后一部分时,我得到了错误
Traceback (most recent call last):
File "/Users/shoot_station_5/Documents/scripts/walkdelete.py", line 16, in <module>
if time.ctime(os.path.getmtime(_dir)) < cutoff:
File "/anaconda3/lib/python3.6/genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [Errno 2] No such file or directory: 'dont_delete'
我正在尝试删除称为垃圾箱的文件夹,因为它的时间超过30秒(出于测试目的,实际上希望是3个月),我怎么会收到没有此类文件或目录错误的信息?
答案 0 :(得分:0)
使用os.path.join(root, _dir)
例如:
import os, sys, time
from subprocess import call
import path
now = time.time()
cutoff = now - (30)#(91 * 86400)
path = '/users/shoot_station_5/documents/folderfordeletetest/'
for root, d_names, f_names in os.walk(path):
print (root, d_names, f_names)
for _dir in d_names:
if time.ctime(os.path.getmtime(os.path.join(root, _dir))) < cutoff:
print (_dir)
答案 1 :(得分:0)
除非终端位于该目录中,否则您不能使用absolute path
。
改为执行此操作:
os.chdir(r"C:\Users\rajat.prakash\Downloads")
fresh = max(latest_file, key = os.path.getctime)
print(fresh)
它将打印最新下载的Excel报告,但首先更改目录。