MyInternships.in

Python Modules & Packages

Python os and sys Modules

The os module lets Python talk to your operating system's files and folders, while sys gives you access to command-line arguments and interpreter-level settings.


The os Module: Working With Your File System

The os module bridges Python and your operating system, letting you find your current folder, list files, read environment variables, and build file paths that work correctly on Windows, macOS, and Linux alike.

Finding and Listing the Current Folder

os.getcwd() returns your current working directory as a string, and os.listdir() lists every file and folder inside a given directory.

getcwd() and listdir()
Python
import os

print(os.getcwd())
print(os.listdir("."))

Building File Paths With os.path

Rather than joining folder names and filenames with plain strings, os.path.join() builds correct paths automatically for whichever operating system your code runs on.

os.path
Python
file_path = os.path.join("data", "students.csv")
print(file_path)
print(os.path.exists(file_path))

Reading Environment Variables

os.environ acts like a dictionary of environment variables set on your machine, often used to safely store secrets like API keys outside of your source code.

os.environ
Python
print(os.environ.get("HOME"))

The sys Module: Talking to the Interpreter

While os deals with the operating system, sys deals with the Python interpreter itself — reading command-line arguments, stopping a script early, or inspecting where Python looks for modules.

Reading Command-Line Arguments With sys.argv

sys.argv is a list of the arguments typed after your script's name on the command line, with the script name itself always at index 0.

greet.py
Python
import sys

name = sys.argv[1]
print(f"Hello, {name}!")
Running with an argument
Terminal
python greet.py Priya

Exiting a Script and Checking sys.path

sys.exit() stops a program immediately, optionally with an exit code, while sys.path lists the folders Python searches through when you write an import statement.

sys.exit() and sys.path
Python
import sys

if len(sys.argv) < 2:
    print("Missing an argument!")
    sys.exit(1)

print(sys.path)
💡

Use os for anything involving files, folders, and paths, and use sys for anything involving the running script or interpreter itself.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships