Introduction
When writing scripts that interact with the operating system or command-line arguments, Python offers two powerful built-in modules: os
and sys
. These modules let you handle file paths, environment variables, and system parameters with ease. In this article, we’ll break down how to use them effectively.
Working with the os Module
The os
module helps you interact with the operating system. Here are some basic tasks:
os.getcwd()
— Get the current working directoryos.listdir()
— List files and directoriesos.makedirs()
— Create directories recursivelyos.environ
— Access environment variables
Example:
import os
print("Current directory:", os.getcwd())
print("Files:", os.listdir())
Working with the sys Module
The sys
module allows access to variables used or maintained by the interpreter:
sys.argv
— Get command-line argumentssys.exit()
— Exit from the scriptsys.path
— List of module search paths
Example:
import sys
print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
Conclusion
The os
and sys
modules are essential for any Python script that interacts with the environment or user inputs. Mastering them will give you greater control and flexibility in automation and scripting tasks.
Related Links

Python File Handling Basics: Reading, Writing, and Using with
IntroductionWorking with files is a common task in many Python projects—whether it's reading configuration files, s...
Comment