Working with the os Module and Directories in Python

Python provides a powerful os module that allows you to interact with the operating system, enabling you to perform various tasks related to file and directory manipulation, process management, and environment variables. In this article, we will explore the capabilities of the os module. The examples include creating directories, populating them with files, and listing their contents.

Using the Python os Module to Work with Directories

Let’s use the os module with to create a directory, populate it with dummy files, and list its contents.

Creating a Directory and File Listing

import os

# Specify the directory name
directory_name = "example_directory"

# Create the directory
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created successfully.")

# Change the current working directory to the newly created directory
os.chdir(directory_name)

# List of dummy file names
dummy_files = ["file1.txt", "file2.txt", "file3.txt"]

# Create dummy files
for file_name in dummy_files:
    with open(file_name, "w") as file:
        file.write(f"This is a dummy file: {file_name}")

print("Dummy files created successfully.")

# List directory contents
directory_contents = os.listdir()

print(f"\nContents of '{directory_name}':")
for item in directory_contents:
    print(item)

Below are some snippets for specific directory tasks with the os module:

Creating a Directory

The os.mkdir() function enables you to create a new directory:

import os
os.mkdir("new_directory")

Removing a Directory

Use os.rmdir() to remove an empty directory:

import os
os.rmdir("directory_to_remove")

Changing the Current Working Directory

The os.chdir() function changes the current working directory:

import os
os.chdir("new_working_directory")

Listing Directory Contents

os.listdir() returns a list containing the names of entries in a given directory:

import os
contents = os.listdir("directory_path")

File and Directory Existence Check

Use os.path.exists() to check if a file or directory exists:

import os
if os.path.exists("file_or_directory_path"):
    print("Exists!")

File Operations with Python os Module

File Renaming

os.rename() allows you to rename a file or directory:

import os
os.rename("old_name.txt", "new_name.txt")

File and Directory Removal

os.remove() removes a file, while os.rmdir() removes an empty directory:

import os
os.remove("file_to_remove.txt")
os.rmdir("empty_directory_to_remove")

File Path Manipulation

The os.path module provides functions for common pathname manipulations:

import os
path = os.path.join("folder", "file.txt")

Process Management with Python os Module

Running Shell Commands

os.system() allows you to execute shell commands:

import os
os.system("ls -l")

Process Termination

os.kill() can be used to send signals to processes:

import os
os.kill(process_id, signal)

Environment Variables with Python os Module

Accessing Environment Variables

os.environ provides access to environment variables:

import os
print(os.environ['HOME'])

Setting Environment Variables

You can use os.environ to set environment variables:

import os
os.environ['MY_VARIABLE'] = 'my_value'

This article provides an in-depth exploration of the os module in Python, covering file and directory operations, process management, and environment variables. The practical example demonstrates how to integrate these concepts when working with directories in Python.

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *