gpt4 book ai didi

python - 在 Python 中删除旧目录

转载 作者:行者123 更新时间:2023-11-28 19:51:50 25 4
gpt4 key购买 nike

我有几个目录,我想删除超过 7 天的目录。我已经实现了代码,但它似乎不起作用。谁能看出我哪里出错了?

def delete_sandbox():

for directories in os.listdir(os.getcwd()):

if not os.path.isdir(directories) or not os.stat(directories).st_ctime < time.time()-(7*24*3600):
continue
os.chdir(directories)
drop_sandbox()
os.chdir(rootDir)
os.system("sudo rm -rf "+directories)
print 'Folders older than 7 days old dropped and removed'

感谢您的帮助

沙箱会丢弃但不会删除的文件夹。我希望程序进入这些文件夹中的每一个,放下沙箱,回到根目录并删除所有旧目录。当我这样做时,文件夹仍然存在。

当我通过存储在文件夹名称中的字符串日期删除目录时,此功能也有效。但是现在我正在尝试获取它已停止工作的时间戳。

我已经测试了 'rm -rf'+directories,它不会删除旧文件夹。当我尝试 shutil.rmtree 时,我收到错误消息:

Traceback (most recent call last):
File "yep.py", line 21, in <module>
delete_sandbox()
File "yep.py", line 18, in delete_sandbox
shutil.rmtree(directories)
File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'Debug'

有没有其他方法可以删除这些文件夹?

我让它工作了,我使用了 shutil.rmtree 并且一切似乎都有效。谢谢你的帮助。修改后的代码为:

def delete_sandbox():

for directories in os.listdir(os.getcwd()):

if not os.path.isdir(directories) or not os.stat(directories).st_ctime < time.time()-(sbox_age):
continue
os.chdir(directories)
drop_sandbox()
os.chdir(rootDir)
shutil.rmtree(directories)
print 'Sandboxes older than 7 days old dropped and removed'

delete_sandbox()

最佳答案

import os
import time
import shutil
numdays = 86400*7
now = time.time()
directory=os.path.join("/home","path")
for r,d,f in os.walk(directory):
for dir in d:
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
print "removing ",os.path.join(r,dir)
# shutil.rmtree(os.path.join(r,dir)) #uncomment to use
except Exception,e:
print e
pass
else:
print "some message for success"

关于python - 在 Python 中删除旧目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2237909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com