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

前端 未结 10 617
无人及你
无人及你 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 00:43

    I think the new pathlib thingy together with the arrow module for dates make for neater code.

    from pathlib import Path
    import arrow
    
    filesPath = r"C:\scratch\removeThem"
    
    criticalTime = arrow.now().shift(hours=+5).shift(days=-7)
    
    for item in Path(filesPath).glob('*'):
        if item.is_file():
            print (str(item.absolute()))
            itemTime = arrow.get(item.stat().st_mtime)
            if itemTime < criticalTime:
                #remove it
                pass
    
    • pathlib makes it easy to list the directory contents, to access file characteristics such as as creation times and to get full paths.
    • arrow makes calculations of times easier and neater.

    Here's the output showing the full paths offered by pathlib. (No need to join.)

    C:\scratch\removeThem\four.txt
    C:\scratch\removeThem\one.txt
    C:\scratch\removeThem\three.txt
    C:\scratch\removeThem\two.txt
    

提交回复
热议问题