Does Python have a module to display when a file has been last modified?

Also, how do you get the file length?

Recommended Answers

All 2 Replies

The functions are contained in module os. Function os.path.getmtime() gives you the last modified time in seconds since the beginning of 1/1/1970 (epoch). You have to do some formatting with module time functions to make it readable for the ordinary mortal.

The size of the file is returned by os.path.getsize() in bytes, convert to kilobytes and format the result.

import os
import time

# pick a file you have in the working folder ...
fname = ""

print "File was last modified (12 hour format):"
print time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(fname)))

fsize = os.path.getsize(fname)
print "size = %0.1f kb" % float(fsize/1000.0)

possible result:
File was last modified (12 hour format):
01/25/2003 11:38:30 AM
size = 5.8 kb

Similarly function os.path.getatime() gives the last access time.

A kbyte is 1024 bytes. This would be more correct:

fsize = os.path.getsize(fname) 
print "size = %0.1f kb" % float(fsize/1024.0)
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.