简体   繁体   中英

Is there a better way to delete files that are a month old in python?

I have built a script that generates files daily and names them by the date that they are generated. However, I then need to delete these files after 1 month, and have found it to be a bit confusing. I believe that the following will work, but I would like to know if Python has a built in feature that allows for this a bit more Pythonicly and elegently.

Note that this code handles files that are at the end of a month with more days than the following month by deleting all files from last month when it reaches the last day of this month.

if today.month != 1:
    if today.day == days_in_month[today.month] and days_in_month[today.month] < days_in_month[today.month - 1]:
        for x in range(days_in_month[today.month],days_in_month[today.month-1]+1):
            date = date(today.year,today.month-1,x)

            fname = str(date)+".stub"
            remove(fname)
else:
    date = date(today.year-1,12,x)

    fname = str(date)+".stub"
    remove(fname)

Take a look at Python's datetime module, it has some classes that should simplify this a lot. You should be able to create a datetime.datetime object from your file name using datetime.datetime.strptime() , and another for the current time using datetime.datetime.now() . You can then subtract one from the other to get a datetime.timedelta object that you can use to figure out the difference between the dates.

Rather than looking at the filenames to determine the age, you could use the creation time.

Something like:

import os
import datetime

path = "/path/to/files"    

for file in os.listdir(path):
    fullpath   = os.path.join(path,file)    # turns 'file1.txt' into '/path/to/file1.txt'
    timestamp  = os.stat(fullpath).st_ctime # get timestamp of file
    createtime = datetime.datetime.fromtimestamp(timestamp)
    now        = datetime.datetime.now()
    delta      = now - createtime
    if delta.days > 30:
        os.remove(fullpath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM