Nearby lessons
97 of 159Python - OS Commands and File Statistics
📌 What You Will Learn
- Execute operating system commands using os.system()
- Get complete file statistics using os.stat()
- Understand the key properties returned by os.stat()
- Read the file size in bytes using st_size
- Convert timestamps to readable dates using datetime.fromtimestamp()
Executing Operating System Commands
Sometimes, from a Python program, we need to execute operating system (DOS) commands.
Python provides the os.system() function for this purpose.
Example
Explanation
The os.system() function executes the specified operating system command.
In Windows, the command dir displays the files and directories in the current working directory.
Common Uses of os.system()
- Display directory contents.
- Create or delete files using OS commands.
- Execute external programs.
- Run batch or shell commands.
Getting File Statistics
Python provides the os.stat() function to obtain complete information about a file.
Important File Properties
| Property | Description |
|---|---|
st_mode |
Protection bits of the file. |
st_ino |
Inode number. |
st_dev |
Device identifier. |
st_nlink |
Number of hard links. |
st_uid |
User ID of the owner. |
st_gid |
Group ID of the owner. |
st_size |
File size in bytes. |
st_atime |
Time of the most recent access. |
st_mtime |
Time of the most recent modification. |
st_ctime |
Time of the most recent metadata change. |
Program: Display All File Statistics
Sample Output
Program: Display Specific File Properties
Sample Output
Explanation
stats.st_size returns the size of the file in bytes.
datetime.fromtimestamp(stats.st_atime) converts the last accessed timestamp into a readable date and time.
datetime.fromtimestamp(stats.st_mtime) converts the last modified timestamp into a readable date and time.
📝 Key Takeaways
- os.system(command) executes an operating system command from Python
- os.stat(filename) returns a file statistics object with complete file information
- st_size returns the file size in bytes
- st_atime and st_mtime return the last access and last modification times as timestamps
- datetime.fromtimestamp() converts a timestamp into a readable date and time
🧠 Test Your Knowledge
6 QuestionsProgress: 0 / 6