如何用纯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 命令简洁的内容也很有启发性。
I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:
find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/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
First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.
Of course, anything with the concision of the bash command would also be illuminating.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是 Bash 命令,而是
find
命令。 如果你真的想将它移植到 Python 上,这是可能的,但你永远无法编写如此简洁的 Python 版本。find
经过 20 多年的优化,在文件系统操作方面表现出色,而 Python 是一种通用编程语言。That's not a Bash command, it's a
find
command. If you really want to port it to Python it's possible, but you'll never be able to write a Python version that's as concise.find
has been optimized over 20 years to be excellent at manipulating filesystems, while Python is a general-purpose programming language.会给你时间。 我建议修复
walk_results[2]
中的这些问题,然后递归调用walk_results[1]
中每个目录的函数。Will give you the mtime. I suggest fixing those in
walk_results[2]
, and then recursing, calling the function for each dir inwalk_results[1]
.这不是开玩笑。 这个 python 脚本将完全执行 bash 脚本所做的事情。
编辑:删除最后一个参数上的反斜杠,因为不需要它。
That is not a joke. This python script will do exactly what the bash one does.
EDIT: Dropped the backslash on the last param because it is not needed.