Converting a system command to python for file search and delete

前端 未结 2 1887
春和景丽
春和景丽 2021-01-15 15:45

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\'

相关标签:
2条回答
  • 2021-01-15 16:33

    use os.popen()

    >>>os.popen("find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file'")
    

    or you can use the subprocess module:

    >>> from subprocess import Popen, PIPE
    >>> stdout= Popen(['ls','-l'], shell=False, stdout=PIPE).communicate()
    >>> print(stdout)
    
    0 讨论(0)
  • 2021-01-15 16:43

    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.

    0 讨论(0)
提交回复
热议问题