I am trying to work out how to remove files from a directory

the files will always have a given extention e.g .txt

I want to remove the filesfrom a specific directory that are older than say 14 days.

Noob to Python sorry if this has been answered elsewhere, all help appreciated.

Recommended Answers

All 8 Replies

You can import subprocess and use getoutput() method to run cmd/shell commands.

Hi I need a bit more help :-( I have Minimal knowledge of Python so would need you to expand

In essence I know the directory (or directories) I want to clear of rubbish, I know the extention or extentions which are no longer of use I simply need to know programatically (Python) how to achieve that!

I can get as far as listing all the files in the directory with that extention, but how do I then expand this to delete files over say 14 days old?

essentially this is all I have got as far as:

import os
import sys
import datetime
import time
import win32api

# dicGeneralInfo = {}

dicGeneralInfo["Current Time"]=time.time()
dicGeneralInfo["Directory"]="C:\blah\blah"

listdir = os.listdir(dicGeneralInfo["Directory"])

for strFile in listdir:

strFullFileName  = dicGeneralInfo["Directory"] + os.sep + strFile

if os.path.isdir(strFullFileName):

    continue

if strFullFileName[-3:].upper() == 'TXT':
now I need to work out how to remove the file(s) if over a certain age
    print strFullFileName

There are probably 1001 ways to do this simple task !

Cheers

All txt files in blah.

import glob

for files in glob.glob(r'C:\blah\blah\*.txt'):
    print files

Run all files through os.stat
What you need is st_mtime,nr 8.

Now you can use time(import time),make a time object for 14_days back.
Make a time object from os.stat(files)[8]call it lastmod_date.
Compare 14_days > lastmod_date use os.remove(files) on files it give back.

Hi I am still struggling with this can you give a worked example from your post above I don't understand :

How to / where to use this : st_mtime,nr 8

How to : Make a time object from os.stat(files)[8]call it lastmod_date.
Compare 14_days > lastmod_date use os.remove(files) on files it give back

Thanks

Test print will show you files to be removed.
If ok remove comment(#) from #os.remove(files)
Remember never use C:\
Use raw string r'C:\' or C:\\ or C:/

import os, glob, time, sys

def file_remove(folder, exp_date, ext):
    '''Remove files older than than set exp_date'''
    for files in glob.glob('{}\*.{}'.format(folder, ext)):
        lastmod_date = time.localtime(os.stat(files)[8])
        ex_date = time.strptime(exp_date, '%d-%m-%Y')
        if  ex_date > lastmod_date:
            try:
                #Test print
                print 'Removing {} {}'.format(files, time.strftime("<Older than %d-%m-%Y>",ex_date))
                #os.remove(files)
            except OSError:
                print 'Could not remove {}'.format(files)

if __name__ == '__main__':
    folder = r'C:\test'
    #Expiration date format DD-MM-YYYY
    exp_date = '07-02-2013'
    #File extension to search for
    ext = 'txt'
    file_remove(folder, exp_date, ext)

Here's a quick example (using what snippsat posted):

import glob
import time
import os
def dl():
    t = 1361455258.34 #a generic moment of time, access time of a file from the folder Blah
    for files in glob.glob(r'E:\blah\*.txt'):
        print(files) #prints the content of the folder
        if (os.stat(files).st_atime>t):
            os.remove(files) #removes desired files
    print('\n\n\n')
    for files in glob.glob(r'E:\blah\*.txt'):
        print(files) #prints the remaining files from the folder
dl()

[Edit]: Also, look above :). 59 seconds earlier than me, but cleaner/better example.

Hi Guys -
All done and whats more I understand HOW .. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.