File module in python has a lot of useful properties. It provides access to various file properties related to time which then can be plugged in use cases like housekeeping, archiving or building logic based the file modified or created time.
os.path.getatime()
returns the access time,
os.path.getmtime()
returns the modification time and
os.path.getctime()
returns the creation time
os.path.getsize()
returns the amount of data in the file, represented in bytes.
# ospath_properties.py
import os.path
import time
print('File :', __file__)
print('Access time :', time.ctime(os.path.getatime(__file__)))
print('Modified time:', time.ctime(os.path.getmtime(__file__)))
print('Change time :', time.ctime(os.path.getctime(__file__)))
print('Size :', os.path.getsize(__file__))
$ python3 ospath_properties.py
File : ospath_properties.py
Access time : Sun Mar 18 16:21:22 2018
Modified time: Fri Nov 11 17:18:44 2016
Change time : Fri Nov 11 17:18:44 2016
Size : 481
A simple script to archive files from given directory using getctime
# housekeep_files.py
import os
import time
from datetime import datetime
# get list of file names
file_names = os.listdir()
archive_days = 90
now = datetime.now()
for file in file_names:
# get created time of file and convert to datetime
created_time = time.ctime(os.path.getctime(files[0]))
created_datetime = datetime.strptime(c_time, "%a %b %d %H:%M:%S %Y")
diff_days = (now - created_datetime).days
# find difference between archive and current day
if days > archive_days:
# logic here to copy or move or remove files
Top comments (0)