我正在用Python编写一个清除脚本。下面的脚本运行良好。该脚本浏览目录列表,并根据每个文件日期删除或保留任何文件。因此,如果X天或X分钟后存在任何文件,这些文件将被删除。你知道吗
purge_files_path = ['x:/path/destination', 'x:/path/destination', ]
kwargs = {"weeks":0, "days": 0, "hours": 0, "minutes": 23}
def purge(purge_files_path, kwargs):
import os
from datetime import datetime, timedelta
for folder in purge_files_path:
for(dir, _, files) in os.walk(folder):
for file in files:
path = os.path.join(dir, file)
if os.path.exists(path):
file_date = datetime.fromtimestamp(os.path.getmtime(path))
delta = datetime.now() - file_date
if delta >= timedelta(**kwargs):
os.remove(path)
现在,我只想添加一个新功能。在删除文件之前,我想把它保存在另一个文件夹中。这可能很简单,但我想保留任何文件的文件夹结构。你知道吗
因此,如果必须清除的文件位于:
c:/source/folder1/folder2/file.txt
必须备份到:
c:/backup/folder1/folder2/file.txt
我可以用shutil.copytree公司,但现有文件夹有一个错误。你知道吗
是的,用
os.rename
代替os.remove
。您可能需要使用relpath
来保留目录结构。只需用以下代码片段替换对os.remove(path)
的调用。你知道吗注意:如果目录在不同的卷上,则需要使用
shutil.move
而不是os.rename
。你知道吗要获得python2支持,您需要像这样删除
exists_ok=True
相关问题 更多 >
编程相关推荐