Python os module

The os module in Python provides functions to interact with the operating system. It includes methods for managing files, directories, environment variables, processes, and system information. Let's explore its capabilities in detail.

1. Getting the Current Working Directory

Use os.getcwd() to get the current working directory of the Python process.
import os

# Get the current working directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)

Output:

Current Directory: /your/current/working/directory
Explanation: os.getcwd() returns the current directory path.

2. Changing the Current Working Directory

Use os.chdir(path) to change the current directory. Replace path with the target directory path.
# Change the working directory
os.chdir("/tmp")
print("Directory after change:", os.getcwd())

Output:

Directory after change: /tmp
Explanation: os.chdir() changes the directory, confirmed by os.getcwd().

3. Listing Files and Directories

os.listdir() lists all files and directories in a specified path.
# List files in the current directory
files = os.listdir(".")
print("Files and directories:", files)

Output:

Files and directories: ['file1.txt', 'file2.txt', 'dir1', 'dir2']
Explanation: os.listdir() returns all files and folders in the current directory.

4. Creating and Removing Directories

Use os.mkdir() to create a directory and os.rmdir() to remove an empty directory.
# Creating a new directory
os.mkdir("test_dir")
print("Created 'test_dir'")

# Removing the directory
os.rmdir("test_dir")
print("Removed 'test_dir'")

Output:

Created 'test_dir'
Removed 'test_dir'
Explanation: os.mkdir() creates a directory, and os.rmdir() removes it if empty.

5. Renaming Files and Directories

os.rename() renames files or directories. Provide the current and new names as arguments.
# Create a file for renaming
with open("old_name.txt", "w") as file:
    file.write("Sample content")

# Rename the file
os.rename("old_name.txt", "new_name.txt")
print("Renamed 'old_name.txt' to 'new_name.txt'")

Output:

Renamed 'old_name.txt' to 'new_name.txt'
Explanation: os.rename() changes a file or directory’s name.

6. Deleting Files

Use os.remove() to delete a file. Be careful, as this action is irreversible.
# Create a file for deletion
with open("file_to_delete.txt", "w") as file:
    file.write("Temporary file content")

# Delete the file
os.remove("file_to_delete.txt")
print("'file_to_delete.txt' deleted")

Output:

'file_to_delete.txt' deleted
Explanation: os.remove() permanently deletes the specified file.

7. Checking if a Path Exists

os.path.exists() checks if a file or directory exists.
# Check if a file exists
path = "example.txt"
if os.path.exists(path):
    print(f"'{path}' exists.")
else:
    print(f"'{path}' does not exist.")

Output:

'example.txt' exists.
Explanation: os.path.exists() verifies the existence of the specified path.

8. Getting File Information

Use os.path.getsize() to get the file size, os.path.abspath() for the absolute path, and os.path.splitext() for the file name and extension separately.
# Get file size
file_size = os.path.getsize("example.txt")
print("File size:", file_size, "bytes")

# Get absolute path
abs_path = os.path.abspath("example.txt")
print("Absolute path:", abs_path)

# Split filename and extension
file_name, file_ext = os.path.splitext("example.txt")
print("File name:", file_name)
print("File extension:", file_ext)

Output:

File size: 34 bytes
Absolute path: /path/to/your/example.txt
File name: example
File extension: .txt
Explanation: These functions provide key details about a file, such as its size and full path.

9. Environment Variables

os.environ accesses system environment variables. You can retrieve, set, or delete them.
# Get an environment variable
home_dir = os.environ.get("HOME")
print("Home Directory:", home_dir)

# Set a new environment variable
os.environ["MY_VAR"] = "TestValue"
print("MY_VAR:", os.environ["MY_VAR"])

# Delete an environment variable
del os.environ["MY_VAR"]

Output:

Home Directory: /home/your_username
MY_VAR: TestValue
Explanation: Environment variables are accessed via os.environ, useful for configuration management.

10. Executing System Commands

Use os.system() to execute system commands from Python.
# List files in the current directory
os.system("ls")

Output:

example.txt
file_to_delete.txt
new_name.txt
Explanation: os.system() runs a command as if it was executed in a terminal.

11. Working with Paths

Common os.path functions:

- os.path.basename(): Gets the file name.
- os.path.dirname(): Gets the directory name.
- os.path.join(): Joins directory and file names to create a full path.
# File path manipulation
path = "/path/to/file.txt"
print("Base name:", os.path.basename(path))
print("Directory name:", os.path.dirname(path))
print("Full path:", os.path.join("/new", "directory", "file.txt"))

Output:

Base name: file.txt
Directory name: /path/to
Full path: /new/directory/file.txt
Explanation: These functions simplify working with file paths.

Summary

The os module is powerful for system-level interactions, enabling file management, environment access, and system commands directly within Python.

Previous: Python IO | Next: Python sys

<
>