- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Introduction
The os module in Python provides functions to interact with the operating system. It allows you to work with files, folders, system paths, and environment variables and execute system commands.
Why Use the os Module?
| Task you want to do | os Module Feature |
|---|---|
| Get current directory | os.getcwd() |
| Change directory | os.chdir() |
| Create/Remove folders | os.mkdir() / os.rmdir() |
| List files and folders | os.listdir() |
| Work with environment variables | os.environ |
| Join file paths safely | os.path.join() |
| Delete a file | os.remove() |
| Run system commands | os.system() |
Importing OS Module
import os
Directory Operations
Get the current working directory
import os
print(os.getcwd())
Change working directory
os.chdir("C:/Users")
List all files and folders
print(os.listdir())
Create and Delete Directories
Create a new folder
os.mkdir("myfolder")
Remove a folder (only if empty)
os.rmdir("myfolder")
Create multiple nested directories
os.makedirs("main/subfolder/new")
Remove nested directories
os.removedirs("main/subfolder/new")
File Handling
Delete a file
os.remove("sample.txt")
Rename a file
os.rename("oldname.txt", "newname.txt")
Path Operations (os.path)
| Function | Description |
|---|---|
os.path.join() | Safely join folder and file names |
os.path.exists() | Check if path/file exists |
os.path.isdir() | Check if the path is file |
os.path.isfile() | Check if the path is a file |
os.path.getsize() | Get file size in bytes |
Example
# This will join the folder path and file name.
path = os.path.join("folder", "file.txt")
# This will return True if path exists.
print(os.path.exists(path))
# get size of file
print(os.path.getsize(path))
Environment Variables
View environment variables
print(os.environ)
Fetch a specific variable
print(os.environ.get("PATH"))
Run System Commands
Open Command Prompt / Terminal command
# get list of file and folder in windos current directory.
os.system("dir") # Windows
# get list of file and folder in linux current directory.
os.system("ls") # Mac/Linux
Examples of Python OS Module
Create a Folder Only If It Doesn’t Exist
import os
folder = "project_data"
if not os.path.exists(folder):
os.mkdir(folder)
print("Folder created")
else:
print("Folder already exists")
List Files Only (Exclude folders)
import os
for item in os.listdir():
if os.path.isfile(item):
print("File:", item)
List Folders Only (Exclude files)
import os
for item in os.listdir():
if os.path.isdir(item):
print("Folder:", item)
Recursively List Files from All Subdirectories
import os
path = "C:/Users"
for root, dirs, files in os.walk(path):
print("Current Path:", root)
print("Folders:", dirs)
print("Files:", files)
print("----------")
Count Number of Files and Folders
import os
files = 0
folders = 0
for item in os.listdir():
if os.path.isfile(item):
files += 1
elif os.path.isdir(item):
folders += 1
print("Files:", files)
print("Folders:", folders)
Copy File to Another Folder (Using os)
osdoesn’t have copy directly, so use system command
import os
os.system("copy source.txt destination\\") # Windows
os.system("cp source.txt destination/") # Linux/Mac
Get File Size in KB / MB
import os
file = "example.txt"
size = os.path.getsize(file) # in bytes
print(size / 1024, "KB")
print(size / (1024*1024), "MB")
Check File Permissions
import os
filepath = "example.txt"
print("Readable:", os.access(filepath, os.R_OK))
print("Writable:", os.access(filepath, os.W_OK))
print("Executable:", os.access(filepath, os.X_OK))
Execute Multiple Commands at Once
import os
os.system("dir && echo Hello World") # Windows
# os.system("ls; echo Hello World") # Linux/Mac
Change File Permission (Linux/Mac)
import os
os.chmod("script.sh", 0o755) # Owner read/write/execute, others read/execute