Converting a system command to python for file search and delete(将系统命令转换为 python 以进行文件搜索和删除)
问题描述
我有一个 cron 作业,它使用以下命令根据文件的年龄删除文件:
I have a cron job that deletes files based on their age using the command:
find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file'
但是我想将该命令集成到一个 python 脚本中,该脚本涉及该任务以及其他也在 cron 上运行的东西.
However I'd like to integrate the command into a python script which involves the task as well as other things that also run on cron.
我知道我可以将命令按原样插入 Python 脚本中,它可能会运行 find,但是我很想知道有一种更以 Python 为中心的方式来完成此任务,以及这可能带来哪些其他好处?
I understand I could just plonk the command as it is into the Python script and it would probably run find, however I'm interested to know there a more Python-centric way to accomplish this and what other benefits might that bring?
推荐答案
我的方法是:
import os
import time
def checkfile(filename):
filestats = os.stat(filename) # Gets infromation on file.
if time.time() - filestats.st_mtime > 120: # Compares if file modification date is more than 120 less than the current time.
os.remove(filename) # Removes file if it needs to be removed.
path = '/path/to/folder'
dirList = os.listdir(path) # Lists specified directory.
for filename in dirList:
checkfile(os.path.join(path, filename)) # Runs checkfile function.
我测试了它,它没有工作,所以我修复了代码,我可以确认它工作.
I tested it, it didn't work, so i fixed the code and i can confirm it works.
这篇关于将系统命令转换为 python 以进行文件搜索和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将系统命令转换为 python 以进行文件搜索和删除
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01