Nearby lessons

97 of 159

Python - 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.

🐍Code Cell
1import os
2 
3os.system(command)
Output
No output captured.

Example

🐍Code Cell
1import os
2 
3os.system("dir")
Output
No output captured.

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.

🐍Code Cell
1import os
2 
3stats = os.stat(filename)
Output
No output captured.

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

🐍Code Cell
1import os
2 
3stats = os.stat("abc.txt")
4 
5print(stats)
Output
No output captured.

Sample Output

Program: Display Specific File Properties

🐍Code Cell
1import os
2from datetime import *
3 
4stats = os.stat("abc.txt")
5 
6print("File Size in Bytes:", stats.st_size)
7 
8print("File Last Accessed Time:",
9 datetime.fromtimestamp(stats.st_atime))
10 
11print("File Last Modified Time:",
12 datetime.fromtimestamp(stats.st_mtime))
Output
No output captured.

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 Questions
Progress: 0 / 6