Get Information About Files Using Python
Python has built-in functions to get information about files and this is very handy because this allows us to get that information for any…
Python has built-in functions to get information about files and this is very handy because this allows us to get that information for any file despite the operating system we use.
To get the size of a file we can use the os.path.getsize() function, it returns the size in bytes.>>> os.path.getsize("t2.txt")
6
To get the file modification time we use the os.path.getmtime() function, it returns a weird long number called epoch time, epoch time which is the number of seconds after 1970–01–01T00:00:00Z UTC.>>> os.path.getmtime("t2.txt")
1657544270.2051177
This can be great when we compare epoch numbers but not very human-readable, to convert epoch to human-readable time we can use the ctime function of the time module that converts epoch seconds to a human-readable form.>>> os.path.getmtime("t2.txt")
1657544270.2051177
>>> import time
>>> print(time.ctime(os.path.getmtime("t2.txt")))
Mon Jul 11 15:57:50 2022
>>>
ctime returns a string that might not be suitable for some operations, you can directly return a datetime object using datetime.>>> import datetime
>>> ts = os.path.getmtime("t2.txt")
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2022, 7, 11, 15, 57, 50, 205118)
To get the absolute path of a file we can use the os.path.abspath() function.>>> os.path.abspath("t2.txt")
'/home/kpatronas/t2.txt'
I hope you enjoyed this article! :)
More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.