Python, Deleting All Files in a Folder Older Than X Days

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

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).

Pythonic way to delete files/folders older than X days

Not a python expert here either, but here's something simple:

  1. Find the date oldest date that you want to keep. Anything older than this will be deleted. Let's say it is the 28/04/2020

  2. From that date, you can build a string "/root_folder/2020/04/28"

  3. List all the files, if their path (as string) is less than the string from the previous step, you can delete them all

Example:

files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.txt' in file:
files.append(os.path.join(r, file))

Source of that snippet: https://mkyong.com/python/python-how-to-list-all-files-in-a-directory/

Now, you can do:

for f in files:
if f < date_limit:
os.remove(f)

Note: This is not optimal

  1. It deletes file by file, but the moment you enter the if you could just delete the whole folder where this file is (but then the list of files points to files that have been deleted).

  2. You actually don't care about the files. You could apply the logic to folders alone and remove them recursively.


Update: doing both steps as we browse the folders:

for r, d, f in os.walk(path):
if( r < date_limit ):
print(f"Deleting {r}")
shutil.rmtree(r)

python delete folders older than x days

#! /usr/bin/python
import time
import ftputil

host = ftputil.FTPHost('ftphost.com', 'username', 'password')
mypath = 'your_path'
now = time.time()
host.chdir(path)
names = host.listdir(host.curdir)
for name in names:
if host.path.getmtime(name) < (now - (5 * 86400)):
if host.path.isfile(name):
host.remove(name)


print 'Closing FTP connection'
host.close()

Delete each file older than X days in Y folder

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)

Python move files older than 7 days but keep the most recent ones

Here is an example of how I would do it.

from re import match
from os import listdir, remove
from os.path import getctime, isfile
from datetime import timedelta, datetime as dt

def time_validator(days):
delta = dt.now() - timedelta(days)
return lambda x: dt.fromtimestamp(getctime(x)) > delta

def files_to_remove(n):
validate = time_validator(7)
files = sorted([
y for x in listdir('/etc')
if isfile((y := f'/etc/{x}'))
and validate(y)
and match('sudoers\.(?!rpm).*', y)
], key=lambda x: getctime(x))
return files[-n:] if len(files) > 20 else []

def remove_files(files):
for file in files: remove(file)

if __name__ == '__main__':
remove_files(files_to_remove(10))

How to delete all the files in sub directories older than x days and not created on Sunday in Python

In order to check the time a file was last edited you want to include two libraries. import os.path, time

First thing you have to take into consideration is which field you want to use from a file, for example:

print("Last Modified: %s" % time.ctime(os.path.getmtime("file.txt")))
# Last Modified: Mon Jul 30 11:10:21 2018
print("Created: %s" % time.ctime(os.path.getctime('file.txt')))
# Created: Tue Jul 31 09:13:23 2018

So you will have to parse this line and look for the fields you want to consider older than x date. Take into consideration to look through the string for Sun, Mon, Tue, Wed, Thur, Fri, Sat for the week values.

fileDate = time.ctime(os.path.getmtime('file.txt'))
if 'Sun' not in fileDate:
# Sun for Sunday is not in the time string so check the date and time

You will have to loop through the files in the subdirectory, check the Created time or Last Modified time, whichever you prefer, and then parse the date and time fields from the string and compare to your case, removing those which you seem fitting to be deleted.

Deleting a file/s within a folder that hasn't been modified in x seconds, continuously

I realised my error:

The modified time was captured when the function was called for the first time, it needed to be run every time. I added the now variable to within the while True loop and all working as expected:

while True:
x = os.listdir(path)
for a in x:
now = time.time()
file_del(a)

Thanks for the assistance, please suggest if question should be deleted.



Related Topics



Leave a reply



Submit