如何用纯Python表达这个Bash命令
我在一个很有用的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命令一样简洁的方式,那就更好了。
4 个回答
这不是一个Bash命令,而是一个find
命令。如果你真的想把它转换成Python代码,也是可以的,但你写出来的Python版本不会那么简洁。find
这个命令经过20年的优化,非常擅长处理文件系统,而Python是一种通用的编程语言。
import subprocess
subprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',
'-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)
这不是开玩笑。这段Python脚本会和那个bash脚本做完全一样的事情。
编辑:最后一个参数的反斜杠去掉了,因为其实不需要。
在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这个时候,我们可以去一些技术论坛,比如StackOverflow,去寻求帮助。在这些论坛上,很多人会分享他们的经验和解决方案。
当你在这些论坛上提问时,记得描述清楚你的问题,包括你遇到的错误信息、你使用的代码,以及你希望实现的目标。这样,别人才能更好地理解你的问题,并给出有效的建议。
另外,查看别人遇到的类似问题和解决方案也是一个很好的学习方式。通过阅读这些内容,你可以学到很多实用的技巧和知识,帮助你更好地解决自己的问题。
总之,技术论坛是一个很好的资源,能帮助你在编程的路上少走弯路。
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))