Python - Working Code Sample for OS and Sys Modules

Python - Working Code Sample for OS and Sys Modules

Working Code Sample for OS and Sys Modules in Python

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.

Introduction to OS and Sys Modules

Importing Required Modules

import os
import sys

These modules are available by default in Python, so no additional installation is required.

Working with OS Module

Getting Current Working Directory

cwd = os.getcwd()
print("Current Working Directory:", cwd)

Changing the Current Working Directory

os.chdir('/tmp')
print("New Working Directory:", os.getcwd())

Listing Files and Folders in Directory

items = os.listdir('.')
print("Directory Contents:", items)

Creating Single and Nested Directories

os.mkdir('example_dir')
os.makedirs('parent/child/grandchild')
print("Directories created.")

Removing Directories

os.rmdir('example_dir')
os.removedirs('parent/child/grandchild')

Renaming Files or Folders

os.rename('old.txt', 'new.txt')
print("File renamed.")

Deleting a File

os.remove('unwanted.txt')

Check if File or Directory Exists

print("Exists:", os.path.exists('file.txt'))
print("Is file:", os.path.isfile('file.txt'))
print("Is directory:", os.path.isdir('folder'))

Path Operations Using os.path

Joining Paths

path = os.path.join('folder', 'subfolder', 'file.txt')
print("Joined path:", path)

Splitting Path into Directory and File

full_path = '/home/user/data.csv'
print("Directory:", os.path.dirname(full_path))
print("Filename:", os.path.basename(full_path))

Getting Absolute Path

print("Absolute path:", os.path.abspath('script.py'))

Getting File Information

Get File Size

print("File size:", os.path.getsize('data.txt'), "bytes")

Last Modified and Access Time

import time

modified = os.path.getmtime('data.txt')
accessed = os.path.getatime('data.txt')

print("Modified:", time.ctime(modified))
print("Accessed:", time.ctime(accessed))

Accessing Environment Variables

List All Environment Variables

env = os.environ
print(env)

Access a Specific Environment Variable

home = os.environ.get('HOME')
print("Home Directory:", home)

Set and Modify Environment Variable

os.environ['MY_VAR'] = 'TestValue'
print("MY_VAR:", os.environ['MY_VAR'])

Process Management with OS

Get Current and Parent Process IDs

print("Current PID:", os.getpid())
print("Parent PID:", os.getppid())

Execute a Shell Command

os.system('echo Hello from shell')

Walking Through Directories

Using os.walk

for root, dirs, files in os.walk('.'):
    print("Directory:", root)
    print("Subdirectories:", dirs)
    print("Files:", files)

Common File Utilities

Cleanup Files with Extension

for filename in os.listdir('.'):
    if filename.endswith('.log'):
        os.remove(filename)
        print("Deleted:", filename)

Backup Files

import shutil

def backup(file):
    if os.path.exists(file):
        shutil.copy(file, file + '.bak')
        print("Backup created for", file)

backup('sample.txt')

Working with Sys Module

Get Command-Line Arguments

print("All arguments:", sys.argv)

if len(sys.argv) > 1:
    print("Script received argument:", sys.argv[1])

Exit from Python Program

print("Exiting now...")
sys.exit(0)

Python Version Information

print("Python version:", sys.version)
print("Version info:", sys.version_info)

System Path List

print("System path:", sys.path)

Adding Directory to Module Search Path

sys.path.append('/my/custom/modules')

Standard Input and Output

sys.stdout.write("Hello via stdout\n")
user_input = sys.stdin.readline()
print("You typed:", user_input)

Exception Hook Example

def custom_hook(exctype, value, traceback):
    print("An error occurred:", value)

sys.excepthook = custom_hook
raise ValueError("This will trigger custom hook")

Combining OS and Sys for Real Use Cases

Example 1: CLI File Checker

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.")

Example 2: Environment-Specific Behavior

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...")

Example 3: Script Location and Resources

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)

Handling Errors

File Not Found

try:
    os.remove('missing.txt')
except FileNotFoundError:
    print("File not found.")

Permission Error

try:
    os.remove('/etc/important')
except PermissionError:
    print("Permission denied.")

Invalid Arguments

if len(sys.argv) != 3:
    print("Usage: python script.py input.txt output.txt")
    sys.exit(1)

Advanced Tips

Set Default Encoding

print("Encoding:", sys.getdefaultencoding())

Redirect Output to a File

with open('output.txt', 'w') as f:
    sys.stdout = f
    print("This will go to output.txt")
    sys.stdout = sys.__stdout__

Check Platform

print("Platform:", sys.platform)
if sys.platform == "win32":
    print("Running on Windows")
elif sys.platform == "linux":
    print("Running on Linux")

Summary of os and sys Functions

  • os.getcwd(), os.chdir() - Directory management
  • os.mkdir(), os.makedirs() - Directory creation
  • os.remove(), os.rename() - File management
  • os.environ, os.system() - Environment and shell
  • os.path - Path operations
  • sys.argv, sys.exit() - CLI and exit
  • sys.version, sys.path - Runtime info

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.

logo

Python

Beginner 5 Hours
Python - Working Code Sample for OS and Sys Modules

Working Code Sample for OS and Sys Modules in Python

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.

Introduction to OS and Sys Modules

Importing Required Modules

import os import sys

These modules are available by default in Python, so no additional installation is required.

Working with OS Module

Getting Current Working Directory

cwd = os.getcwd() print("Current Working Directory:", cwd)

Changing the Current Working Directory

os.chdir('/tmp') print("New Working Directory:", os.getcwd())

Listing Files and Folders in Directory

items = os.listdir('.') print("Directory Contents:", items)

Creating Single and Nested Directories

os.mkdir('example_dir') os.makedirs('parent/child/grandchild') print("Directories created.")

Removing Directories

os.rmdir('example_dir') os.removedirs('parent/child/grandchild')

Renaming Files or Folders

os.rename('old.txt', 'new.txt') print("File renamed.")

Deleting a File

os.remove('unwanted.txt')

Check if File or Directory Exists

print("Exists:", os.path.exists('file.txt')) print("Is file:", os.path.isfile('file.txt')) print("Is directory:", os.path.isdir('folder'))

Path Operations Using os.path

Joining Paths

path = os.path.join('folder', 'subfolder', 'file.txt') print("Joined path:", path)

Splitting Path into Directory and File

full_path = '/home/user/data.csv' print("Directory:", os.path.dirname(full_path)) print("Filename:", os.path.basename(full_path))

Getting Absolute Path

print("Absolute path:", os.path.abspath('script.py'))

Getting File Information

Get File Size

print("File size:", os.path.getsize('data.txt'), "bytes")

Last Modified and Access Time

import time modified = os.path.getmtime('data.txt') accessed = os.path.getatime('data.txt') print("Modified:", time.ctime(modified)) print("Accessed:", time.ctime(accessed))

Accessing Environment Variables

List All Environment Variables

env = os.environ print(env)

Access a Specific Environment Variable

home = os.environ.get('HOME') print("Home Directory:", home)

Set and Modify Environment Variable

os.environ['MY_VAR'] = 'TestValue' print("MY_VAR:", os.environ['MY_VAR'])

Process Management with OS

Get Current and Parent Process IDs

print("Current PID:", os.getpid()) print("Parent PID:", os.getppid())

Execute a Shell Command

os.system('echo Hello from shell')

Walking Through Directories

Using os.walk

for root, dirs, files in os.walk('.'): print("Directory:", root) print("Subdirectories:", dirs) print("Files:", files)

Common File Utilities

Cleanup Files with Extension

for filename in os.listdir('.'): if filename.endswith('.log'): os.remove(filename) print("Deleted:", filename)

Backup Files

import shutil def backup(file): if os.path.exists(file): shutil.copy(file, file + '.bak') print("Backup created for", file) backup('sample.txt')

Working with Sys Module

Get Command-Line Arguments

print("All arguments:", sys.argv) if len(sys.argv) > 1: print("Script received argument:", sys.argv[1])

Exit from Python Program

print("Exiting now...") sys.exit(0)

Python Version Information

print("Python version:", sys.version) print("Version info:", sys.version_info)

System Path List

print("System path:", sys.path)

Adding Directory to Module Search Path

sys.path.append('/my/custom/modules')

Standard Input and Output

sys.stdout.write("Hello via stdout\n") user_input = sys.stdin.readline() print("You typed:", user_input)

Exception Hook Example

def custom_hook(exctype, value, traceback): print("An error occurred:", value) sys.excepthook = custom_hook raise ValueError("This will trigger custom hook")

Combining OS and Sys for Real Use Cases

Example 1: CLI File Checker

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.")

Example 2: Environment-Specific Behavior

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...")

Example 3: Script Location and Resources

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)

Handling Errors

File Not Found

try: os.remove('missing.txt') except FileNotFoundError: print("File not found.")

Permission Error

try: os.remove('/etc/important') except PermissionError: print("Permission denied.")

Invalid Arguments

if len(sys.argv) != 3: print("Usage: python script.py input.txt output.txt") sys.exit(1)

Advanced Tips

Set Default Encoding

print("Encoding:", sys.getdefaultencoding())

Redirect Output to a File

with open('output.txt', 'w') as f: sys.stdout = f print("This will go to output.txt") sys.stdout = sys.__stdout__

Check Platform

print("Platform:", sys.platform) if sys.platform == "win32": print("Running on Windows") elif sys.platform == "linux": print("Running on Linux")

Summary of os and sys Functions

  • os.getcwd(), os.chdir() - Directory management
  • os.mkdir(), os.makedirs() - Directory creation
  • os.remove(), os.rename() - File management
  • os.environ, os.system() - Environment and shell
  • os.path - Path operations
  • sys.argv, sys.exit() - CLI and exit
  • sys.version, sys.path - Runtime info

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.

Frequently Asked Questions for 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.


Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

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. Performance: Java has a higher performance than Python due to its static typing and optimization by the Java Virtual Machine (JVM).

Python can be considered beginner-friendly, as it is a programming language that prioritizes readability, making it easier to understand and use. Its syntax has similarities with the English language, making it easy for novice programmers to leap into the world of development.

To start coding in Python, you need to install Python and set up your development environment. You can download Python from the official website, use Anaconda Python, or start with DataLab to get started with Python in your browser.

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.

Python alone isn't going to get you a job unless you are extremely good at it. Not that you shouldn't learn it: it's a great skill to have since python can pretty much do anything and coding it is fast and easy. It's also a great first programming language according to lots of programmers.

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

  • Choose Your Focus. Python is a versatile language with a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.
  • Practice regularly.
  • Work on real projects.
  • Join a community.
  • Don't rush.
  • Keep iterating.

The following is a step-by-step guide for beginners interested in learning Python using Windows.

  • Set up your development environment.
  • Install Python.
  • Install Visual Studio Code.
  • Install Git (optional)
  • Hello World tutorial for some Python basics.
  • Hello World tutorial for using Python with VS Code.

Best YouTube Channels to Learn Python

  • Corey Schafer.
  • sentdex.
  • Real Python.
  • Clever Programmer.
  • CS Dojo (YK)
  • Programming with Mosh.
  • Tech With Tim.
  • Traversy Media.

Python can be written on any computer or device that has a Python interpreter installed, including desktop computers, servers, tablets, and even smartphones. However, a laptop or desktop computer is often the most convenient and efficient option for coding due to its larger screen, keyboard, and mouse.

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.

  • Google's Python Class.
  • Microsoft's Introduction to Python Course.
  • Introduction to Python Programming by Udemy.
  • Learn Python - Full Course for Beginners by freeCodeCamp.
  • Learn Python 3 From Scratch by Educative.
  • Python for Everybody by Coursera.
  • Learn Python 2 by Codecademy.

  • Understand why you're learning Python. Firstly, it's important to figure out your motivations for wanting to learn Python.
  • Get started with the Python basics.
  • Master intermediate Python concepts.
  • Learn by doing.
  • Build a portfolio of projects.
  • Keep challenging yourself.

Top 5 Python Certifications - Best of 2024
  • PCEP (Certified Entry-level Python Programmer)
  • PCAP (Certified Associate in Python Programmer)
  • PCPP1 & PCPP2 (Certified Professional in Python Programming 1 & 2)
  • Certified Expert in Python Programming (CEPP)
  • Introduction to Programming Using Python by Microsoft.

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.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website, https://www.python.org/, and may be freely distributed.

If you're looking for a lucrative and in-demand career path, you can't go wrong with Python. As one of the fastest-growing programming languages in the world, Python is an essential tool for businesses of all sizes and industries. Python is one of the most popular programming languages in the world today.

line

Copyrights © 2024 letsupdateskills All rights reserved