将系统命令转换为python进行文件搜索和删除 [英] Converting a system command to python for file search and delete

查看:144
本文介绍了将系统命令转换为python进行文件搜索和删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  find / path / to / file 

我有一个cron作业,使用命令删除基于其年龄的文件。 / -type f -mmin +120 | xargs -I file rm'file'

喜欢将命令集成到一个涉及任务的python脚本以及在cron上运行的其他东西。



我知道我可以直接执行命令到Python脚本,它可能会运行查找,但是我有兴趣知道有更多的Python为中心的方式来实现这一点,以及可能带来什么其他好处?

解决方案

我的方法是:

pre $ import $
$ b $
$ b def checkfile(文件名):
filestats = os.stat(文件名)#获取文件信息。
if time.time() - filestats.st_mtime> 120:#比较文件修改日期是否比当前时间少120。
os.remove(文件名)#删除需要删除的文件。

path ='/ path / to / folder'

dirList = os.listdir(path)#列出指定的目录。
用于dirList中的文件名:
checkfile(os.path.join(path,filename))#运行checkfile函数。

编辑:我测试过了,它没有工作,所以我修复了代码,我可以确认它的工作。


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'

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.

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?

解决方案

My method would be:

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.

Edit: I tested it, it didn't work, so i fixed the code and i can confirm it works.

这篇关于将系统命令转换为python进行文件搜索和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆