6

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?

zondo
  • 19,901
  • 8
  • 44
  • 83
Edward Shaw
  • 71
  • 1
  • 1
  • 2
  • 4
    does older mean "creation date", "modification date" or "last access"? – Vadim Key May 23 '16 at 19:42
  • Check [this](http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python) and [this](http://stackoverflow.com/questions/6996603/how-do-i-delete-a-file-or-folder-in-python) – Avantol13 May 23 '16 at 19:51

3 Answers3

21

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))
Vedang Mehta
  • 2,214
  • 9
  • 22
1

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 :)
Vadim Key
  • 1,242
  • 6
  • 15
  • Note: `st_ctime` does not stand for creation time. "It's the change time of the inode. It's updated whenever the inode is modified, e.g. metadata modifications like permission changes, link/unlink of hard links etc." So you might want to use something else depending on the data you process. I use `st_mtime` for example that is the date of last modification. – Noah Krasser Dec 03 '18 at 12:30
1

Based in Vadim solution a more flexible approach Remember os.unlink(fileWithPath) removes everything in that folder older than X days, so be careful.

############ DELETE OLDER THAN X ############
current_time = time.time()
daysToDelete = 7
directory = '/absolute/path/to/folder/'

for dirpath,_,filenames in os.walk(directory):
    for f in filenames:
        fileWithPath = os.path.abspath(os.path.join(dirpath, f))
        creation_time = os.path.getctime(fileWithPath)
        print("file available:",fileWithPath)
        if (current_time - creation_time) // (24 * 3600) >= daysToDelete:
            os.unlink(fileWithPath)
            print('{} removed'.format(fileWithPath))
            print("\n")
        else:
            print('{} not removed'.format(fileWithPath))
ssalgado
  • 43
  • 5