Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Deleting files of a certain age

Tags:

python

So at the moment I'm trying to delete files listed in the directory that are 1 minute old, I will change that value once I have the script working.
The code below returns the error: AttributeError: 'str' object has no attribute 'mtime'

import time
import os 
#from path import path

seven_days_ago = time.time() - 60
folder = '/home/rv/Desktop/test'

for somefile in os.listdir(folder):
    if int(somefile.mtime) < seven_days_ago:
        somefile.remove()
like image 637
Phil Avatar asked Jul 27 '10 16:07

Phil


People also ask

How do you delete specific files in Python?

All you need to do to remove a file is call os. remove() with the appropriate filename and path (Python defaults to the current directory, so you don't need to specify a path if the file you want to remove is in the default directory).


2 Answers

import time
import os

one_minute_ago = time.time() - 60 
folder = '/home/rv/Desktop/test'
os.chdir(folder)
for somefile in os.listdir('.'):
    st=os.stat(somefile)
    mtime=st.st_mtime
    if mtime < one_minute_ago:
        print('remove %s'%somefile)
        # os.unlink(somefile) # uncomment only if you are sure
like image 174
unutbu Avatar answered Oct 23 '22 13:10

unutbu


That's because somefile is a string, a relative filename. What you need to do is to construct the full path (i.e., absolute path) of the file, which you can do with the os.path.join function, and pass it to the os.stat, the return value will have an attribute st_mtime which will contain your desired value as an integer.

like image 38
SilentGhost Avatar answered Oct 23 '22 15:10

SilentGhost