In this section, we will explore how to perform various file and directory operations using Python. This includes creating, deleting, and navigating directories, as well as manipulating files within those directories. These operations are essential for tasks such as organizing data, automating backups, and managing application resources.

Key Concepts

  1. File Operations:

    • Creating files
    • Deleting files
    • Renaming files
    • Moving files
  2. Directory Operations:

    • Creating directories
    • Deleting directories
    • Listing directory contents
    • Navigating directories
  3. Useful Modules:

    • os
    • shutil
    • pathlib

File Operations

Creating Files

To create a file, you can use the open() function with the mode 'w' (write) or 'a' (append). If the file does not exist, it will be created.

# Creating a new file
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

Deleting Files

To delete a file, you can use the os.remove() function.

import os

# Deleting a file
os.remove('example.txt')

Renaming Files

To rename a file, use the os.rename() function.

# Renaming a file
os.rename('old_name.txt', 'new_name.txt')

Moving Files

To move a file, you can use the shutil.move() function.

import shutil

# Moving a file
shutil.move('source.txt', 'destination_folder/source.txt')

Directory Operations

Creating Directories

To create a directory, use the os.makedirs() function.

# Creating a new directory
os.makedirs('new_directory')

Deleting Directories

To delete a directory, use the os.rmdir() function for an empty directory or shutil.rmtree() for a directory with contents.

# Deleting an empty directory
os.rmdir('empty_directory')

# Deleting a directory with contents
shutil.rmtree('directory_with_contents')

Listing Directory Contents

To list the contents of a directory, use the os.listdir() function.

# Listing directory contents
contents = os.listdir('some_directory')
print(contents)

Navigating Directories

To change the current working directory, use the os.chdir() function.

# Changing the current working directory
os.chdir('new_working_directory')

Practical Examples

Example 1: Organizing Files by Extension

This script organizes files in the current directory into subdirectories based on their file extensions.

import os
import shutil

def organize_files_by_extension(directory):
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            extension = filename.split('.')[-1]
            extension_dir = os.path.join(directory, extension)
            if not os.path.exists(extension_dir):
                os.makedirs(extension_dir)
            shutil.move(os.path.join(directory, filename), os.path.join(extension_dir, filename))

# Organize files in the current directory
organize_files_by_extension('.')

Example 2: Backup Script

This script creates a backup of a specified directory by copying its contents to a backup directory.

import os
import shutil
from datetime import datetime

def backup_directory(source_dir, backup_dir):
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    backup_path = os.path.join(backup_dir, f'backup_{timestamp}')
    shutil.copytree(source_dir, backup_path)
    print(f'Backup created at {backup_path}')

# Backup the 'data' directory to the 'backups' directory
backup_directory('data', 'backups')

Exercises

Exercise 1: Create a Directory and File

  1. Create a directory named test_directory.
  2. Inside test_directory, create a file named test_file.txt and write the text "This is a test file."

Solution:

import os

# Create a directory
os.makedirs('test_directory')

# Create a file and write text to it
with open('test_directory/test_file.txt', 'w') as file:
    file.write("This is a test file.")

Exercise 2: List and Delete Files

  1. List all files in the current directory.
  2. Delete all files with the .tmp extension.

Solution:

import os

# List all files in the current directory
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print("Files in current directory:", files)

# Delete all .tmp files
for file in files:
    if file.endswith('.tmp'):
        os.remove(file)
        print(f"Deleted {file}")

Summary

In this section, we covered various file and directory operations in Python, including creating, deleting, renaming, and moving files and directories. We also explored practical examples and exercises to reinforce these concepts. Understanding these operations is crucial for managing files and directories effectively in your Python applications.

Python Programming Course

Module 1: Introduction to Python

Module 2: Control Structures

Module 3: Functions and Modules

Module 4: Data Structures

Module 5: Object-Oriented Programming

Module 6: File Handling

Module 7: Error Handling and Exceptions

Module 8: Advanced Topics

Module 9: Testing and Debugging

Module 10: Web Development with Python

Module 11: Data Science with Python

Module 12: Final Project

© Copyright 2024. All rights reserved