1,105,546 Community Members

Noobie to Python Question Windows Files

Member Avatar
SteveA
Newbie Poster
4 posts since Feb 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Member Avatar
np complete
Posting Pro in Training
414 posts since Sep 2010
Reputation Points: 8 [?]
Q&As Helped to Solve: 38 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
SteveA
Newbie Poster
4 posts since Feb 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
snippsat
Veteran Poster
1,041 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 382 [?]
Skill Endorsements: 10 [?]
 
0
 

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.

Member Avatar
SteveA
Newbie Poster
4 posts since Feb 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
snippsat
Veteran Poster
1,041 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 382 [?]
Skill Endorsements: 10 [?]
 
0
 

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)
Member Avatar
Lucaci Andrew
Master Poster
746 posts since Jan 2012
Reputation Points: 128 [?]
Q&As Helped to Solve: 116 [?]
Skill Endorsements: 18 [?]
 
0
 

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.

Member Avatar
SteveA
Newbie Poster
4 posts since Feb 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 
Question Answered as of 1 Year Ago by snippsat, Ene Uran, np complete and 1 other
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article