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

前端 未结 10 633
无人及你
无人及你 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:03

    os.listdir() returns a list of bare filenames. These do not have a full path, so you need to combine it with the path of the containing directory. You are doing this when you go to delete the file, but not when you stat the file (or when you do isfile() either).

    Easiest solution is just to do it once at the top of your loop:

    f = os.path.join(path, f)
    

    Now f is the full path to the file and you just use f everywhere (change your remove() call to just use f too).

提交回复
热议问题