我在一个有用的 Bash 脚本中有这一行,我还没有设法将其翻译成 Python,其中“a”是用户输入的要归档文件的天数:
find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
我熟悉最通用的跨平台元素的 os.name 和 getpass.getuser。我也有这个功能来生成相当于 ~/podcasts/current 中所有文件的全名列表:
def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
首先,必须有更好的方法来做到这一点,欢迎提出任何建议。无论哪种方式,例如,“AllFiles('/users/me/music/itunes/itunes music/podcasts')”在 Windows 上给出了相关列表。大概我应该能够检查这个列表并调用 os.stat(list_member).st_mtime 并将所有超过特定天数的东西移动到存档中;我有点卡在这一点上。
当然,任何具有 bash 命令简洁性的内容也会很有启发性。
请您参考如下方法:
import os
import shutil
from os import path
from os.path import join, getmtime
from time import time
archive = "bak"
current = "cur"
def archive_old_versions(days = 3):
for root, dirs, files in os.walk(current):
for name in files:
fullname = join(root, name)
if (getmtime(fullname) < time() - days * 60 * 60 * 24):
shutil.move(fullname, join(archive, name))
