Python 删除超过 7 天的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37399210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete files that are older than 7 days
提问by Edward Shaw
I have seen some posts to delete all the files (not folders) in a specific folder, but I simply don't understand them.
我看过一些帖子,删除特定文件夹中的所有文件(不是文件夹),但我根本不明白它们。
I need to use a UNC path and delete all the files that are older than 7 days.
我需要使用 UNC 路径并删除所有超过 7 天的文件。
Mypath = \files\data\APIArchiveFolder\
Does someone have quick script that they can specifically input the path above into that would delete all files older than 7 days?
有人有快速脚本,他们可以专门输入上面的路径来删除所有超过 7 天的文件吗?
回答by Vedang Mehta
This code removes files in the current working directory that were created >= 7 days ago. Run at your own risk.
此代码删除当前工作目录中 >= 7 天前创建的文件。运行风险自负。
import os
import time
current_time = time.time()
for f in os.listdir():
creation_time = os.path.getctime(f)
if (current_time - creation_time) // (24 * 3600) >= 7:
os.unlink(f)
print('{} removed'.format(f))
回答by Vadim Key
Another version:
另一个版本:
import os
import time
import sys
if len(sys.argv) != 2:
print "usage", sys.argv[0], " <dir>"
sys.exit(1)
workdir = sys.argv[1]
now = time.time()
old = now - 7 * 24 * 60 * 60
for f in os.listdir(workdir):
path = os.path.join(workdir, f)
if os.path.isfile(path):
stat = os.stat(path)
if stat.st_ctime < old:
print "removing: ", path
# os.remove(path) # uncomment when you will sure :)