Python, how to get the details of a file
New Course Coming Soon:
Get Really Good at Git
Given the path to a file, you can get more information about it using several method provided by the os
module:
os.path.getsize()
returns the size of the fileos.path.getmtime()
returns the file last modified dateos.path.getctime()
returns the file creation date (equals to last modified date in Unix systems like macOS)
Here is an example:
import os
filename = '/Users/flavio/test.txt'
print(os.path.getsize(filename))
print(os.path.getmtime(filename))
print(os.path.getctime(filename))
os.stat()
returns all the information you need in a concise way:
import os
filename = '/Users/flavio/test.txt'
print(os.stat(filename))
It returns a os.stat_result
object:
os.stat_result(st_mode=33252, st_ino=34409711, st_dev=16777224, st_nlink=1, st_uid=501, st_gid=20, st_size=189, st_atime=1605428774, st_mtime=1605428773, st_ctime=1605428773)
We have a lot of information here, including:
st_mode
the file type and permissionsst_ino
the inode numberst_dev
the device idst_uid
the file owner idst_gid
the file group idst_size
the file size
and you can reach for individual properties:
import os
filename = '/Users/flavio/test.txt'
stats = os.stat(filename)
print(stats.st_size)
print(stats.st_mtime)
Are you intimidated by Git? Can’t figure out merge vs
rebase? Are you afraid of screwing up something any time
you have to do something in Git? Do you rely on ChatGPT
or random people’s answer on StackOverflow to fix your
problems? Your coworkers are tired of explaining Git to
you all the time? Git is something we all need to use,
but few of us really master it. I created this course to
improve your Git (and GitHub) knowledge at a radical
level. A course that helps you feel less frustrated with
Git. Launching Summer 2024. Join the waiting list!
→ Get my Python Handbook
→ Get my Python Handbook
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X