Converting a system command to python for file search and delete

前端 未结 2 1886
春和景丽
春和景丽 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: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.

提交回复
热议问题