Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files that are older than 7 days

I have seen some posts to delete all the files (not folders) in a specific folder, but I simply don't understand them.

I need to use a UNC path and delete all the files that are older than 7 days.

 Mypath = \\files\data\APIArchiveFolder\

Does someone have quick script that they can specifically input the path above into that would delete all files older than 7 days?

like image 926
Edward Shaw Avatar asked May 23 '16 19:05

Edward Shaw


People also ask

How do I delete files older than a certain date?

You can free up space and keep things organized by only deleting files that are older than a certain number of days in any folder — here's how to do it. To delete files older than 30 days on Windows 10, use the “ForFiles” command. The command is: ForFiles /p “C:\path\to\folder” /s /d -30 /c “cmd /c del /q @file”.


2 Answers

This code removes files in the current working directory that were created >= 7 days ago. Run at your own risk.

import os
import time

current_time = time.time()

for f in os.listdir():
    creation_time = os.path.getctime(f)
    if (current_time - creation_time) // (24 * 3600) >= 7:
        os.unlink(f)
        print('{} removed'.format(f))
like image 104
Vedang Mehta Avatar answered Sep 18 '22 17:09

Vedang Mehta


Another version:

import os
import time
import sys

if len(sys.argv) != 2:
    print "usage", sys.argv[0], " <dir>"
    sys.exit(1)

workdir = sys.argv[1]

now = time.time()
old = now - 7 * 24 * 60 * 60

for f in os.listdir(workdir):
    path = os.path.join(workdir, f)
    if os.path.isfile(path):
        stat = os.stat(path)
        if stat.st_ctime < old:
            print "removing: ", path
            # os.remove(path) # uncomment when you will sure :)
like image 35
Vadim Key Avatar answered Sep 19 '22 17:09

Vadim Key