OS

Working with OS

Python's built-in os module gives your program the power to interact with the operating system which lets you work with files, folders, and system paths.

Importing the OS Module

Before using any features, you need to import the module:

import os

Key Uses of OS

Getting Your Current Working Directory

To find out where your Python script is running:

print(os.getcwd())  # e.g. /Users/adam/Documents/projects

This returns the CWD which is the default location for reading or saving files unless you change it.

Listing Files and Folders in a Directory

You can use os.listdir() with any valid path to list its contents.

print(os.listdir("/Users/adam"))  
# Might return: ['Documents', 'Pictures', 'Downloads']

Joining Paths the Right Way

Instead of manually typing folder paths (which can cause problems on different systems), use os.path.join(). This ensures your code works on Windows, macOS, and Linux.

folder = os.path.join("/Users/adam", "Documents")
print(folder)  # Automatically adds the correct slash

Splitting Paths and Filenames

You can break a full path into directory and file parts with:

path = "/Users/adam/Pictures/image1.png"
(dirname, filename) = os.path.split(path)

print(dirname)   # /Users/adam/Pictures
print(filename)  # image1.png

Then, to separate the filename from its extension:

(module, extension) = os.path.splitext(filename)
print(module)     # image1
print(extension)  # .png

This is useful when renaming files or filtering for .txt or .jpg.

The SYS Module

Sometimes you'll want to interact with command-line arguments or exit a script early. That's where the sys module helps.

import sys
print(sys.argv[0])  # The script's file name
print(sys.argv[1])  # First argument passed by the user

For example, if you run this in the terminal:

python script.py myfile.txt
  • sys.argv[0] is "script.py"
  • sys.argv[1] is "myfile.txt"

You can use sys.exit() to stop the program if something goes wrong. The following stops the program and prints the message to the terminal.

if not os.path.exists("important_file.txt"):
    sys.exit("Error: File not found.")