Search code examples
python-3.xraspbianraspberry-pi3

Delete each file older than X days in Y folder


I wrote this but it doesn't work. In giorni I put the maximum days of stay in the SD andfile_dir is the default location where the files are analyzed.

import os
from datetime import datetime, timedelta

file_dir = "/home/pi/" #location 
giorni = 2 #n max of days

giorni_pass = datetime.now() - timedelta(giorni)

for root, dirs, files in os.walk(file_dir):
    for file in files:
        filetime = datetime.fromtimestamp(os.path.getctime(file))
        if filetime > giorni_pass:
            os.remove(file)

Solution

  • Solved with:

    for file in files:
            path = os.path.join(file_dir, file)
            filetime = datetime.fromtimestamp(os.path.getctime(path))
            if filetime > giorni_pass:
                os.remove(path)
    

    Because "Filenames" contains a list of files whose path name is relative to "file_dir" and to make operations on those files should first get the absolute path, using path = os.path.join(file_dir, file)