Pythonβs os and sys modules are part of the standard library and provide vital functionality for interacting with the operating system and the Python runtime environment. These modules empower developers to perform system-level operations, manipulate the environment, and handle runtime arguments. This document provides a thorough overview along with working examples for both modules in various use cases.
import os
import sys
These modules are available by default in Python, so no additional installation is required.
cwd = os.getcwd()
print("Current Working Directory:", cwd)
os.chdir('/tmp')
print("New Working Directory:", os.getcwd())
items = os.listdir('.')
print("Directory Contents:", items)
os.mkdir('example_dir')
os.makedirs('parent/child/grandchild')
print("Directories created.")
os.rmdir('example_dir')
os.removedirs('parent/child/grandchild')
os.rename('old.txt', 'new.txt')
print("File renamed.")
os.remove('unwanted.txt')
print("Exists:", os.path.exists('file.txt'))
print("Is file:", os.path.isfile('file.txt'))
print("Is directory:", os.path.isdir('folder'))
path = os.path.join('folder', 'subfolder', 'file.txt')
print("Joined path:", path)
full_path = '/home/user/data.csv'
print("Directory:", os.path.dirname(full_path))
print("Filename:", os.path.basename(full_path))
print("Absolute path:", os.path.abspath('script.py'))
print("File size:", os.path.getsize('data.txt'), "bytes")
import time
modified = os.path.getmtime('data.txt')
accessed = os.path.getatime('data.txt')
print("Modified:", time.ctime(modified))
print("Accessed:", time.ctime(accessed))
env = os.environ
print(env)
home = os.environ.get('HOME')
print("Home Directory:", home)
os.environ['MY_VAR'] = 'TestValue'
print("MY_VAR:", os.environ['MY_VAR'])
print("Current PID:", os.getpid())
print("Parent PID:", os.getppid())
os.system('echo Hello from shell')
for root, dirs, files in os.walk('.'):
print("Directory:", root)
print("Subdirectories:", dirs)
print("Files:", files)
for filename in os.listdir('.'):
if filename.endswith('.log'):
os.remove(filename)
print("Deleted:", filename)
import shutil
def backup(file):
if os.path.exists(file):
shutil.copy(file, file + '.bak')
print("Backup created for", file)
backup('sample.txt')
print("All arguments:", sys.argv)
if len(sys.argv) > 1:
print("Script received argument:", sys.argv[1])
print("Exiting now...")
sys.exit(0)
print("Python version:", sys.version)
print("Version info:", sys.version_info)
print("System path:", sys.path)
sys.path.append('/my/custom/modules')
sys.stdout.write("Hello via stdout\n")
user_input = sys.stdin.readline()
print("You typed:", user_input)
def custom_hook(exctype, value, traceback):
print("An error occurred:", value)
sys.excepthook = custom_hook
raise ValueError("This will trigger custom hook")
if len(sys.argv) != 2:
print("Usage: python script.py <filename>")
sys.exit(1)
filename = sys.argv[1]
if os.path.exists(filename):
print("File exists.")
else:
print("File does not exist.")
mode = os.environ.get('APP_MODE', 'development')
print("Running in mode:", mode)
if mode == 'production':
print("Running optimized processes...")
else:
print("Running in debug mode...")
script_path = os.path.abspath(sys.argv[0])
script_dir = os.path.dirname(script_path)
resource_path = os.path.join(script_dir, 'data.json')
print("Script Directory:", script_dir)
print("Resource Path:", resource_path)
try:
os.remove('missing.txt')
except FileNotFoundError:
print("File not found.")
try:
os.remove('/etc/important')
except PermissionError:
print("Permission denied.")
if len(sys.argv) != 3:
print("Usage: python script.py input.txt output.txt")
sys.exit(1)
print("Encoding:", sys.getdefaultencoding())
with open('output.txt', 'w') as f:
sys.stdout = f
print("This will go to output.txt")
sys.stdout = sys.__stdout__
print("Platform:", sys.platform)
if sys.platform == "win32":
print("Running on Windows")
elif sys.platform == "linux":
print("Running on Linux")
In this guide, we explored Pythonβs os and sys modules through practical, working examples. These modules are essential for creating flexible, OS-aware scripts that can handle real-world tasks such as file manipulation, directory traversal, environment configuration, and command-line utilities.
The os module interacts directly with the file system and environment variables, while the sys module handles the runtime state and CLI arguments. When used together, they can automate and control everything from startup behavior to deployment utilities.
Whether you're building administrative tools, scripting system tasks, or creating development frameworks, mastery over these modules will dramatically improve your productivity and control in Python.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved