Python, Deleting all files in a folder older than X days

前端 未结 10 637
无人及你
无人及你 2020-12-08 00:39

I\'m trying to write a python script to delete all files in a folder older than X days. This is what I have so far:

import os, time, sys

path = r\"c:\\user         


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 01:05

    A simple python script to remove /logs/ files older than 10 days

    #!/usr/bin/python
    
    # run by crontab
    # removes any files in /logs/ older than 10 days
    
    import os, sys, time
    from subprocess import call
    
    def get_file_directory(file):
        return os.path.dirname(os.path.abspath(file))
    
    now = time.time()
    cutoff = now - (10 * 86400)
    
    files = os.listdir(os.path.join(get_file_directory(__file__), "logs"))
    file_path = os.path.join(get_file_directory(__file__), "logs/")
    for xfile in files:
        if os.path.isfile(str(file_path) + xfile):
            t = os.stat(str(file_path) + xfile)
            c = t.st_ctime
    
            # delete file if older than 10 days
            if c < cutoff:
                os.remove(str(file_path) + xfile)
    

    With __file__ you can replace by your path.

提交回复
热议问题