An Introduction to the Art of Computer Programming Using Python in the Age of Generative AI

XI. File Handling and I/O

Introduction to File Handling

File handling is an essential part of any programming language, allowing programs to read from and write to files on disk. Python provides a number of functions and methods for these tasks. Proper file handling is crucial for data persistence, configuration management, and data exchange in applications.

Reading and Writing Text Files

You can read and write text files using the built-in open function, along with the read, write, and close methods. The with statement is used to ensure that files are properly closed after their suite has finished.


# Writing to a file
with open('example.txt', 'w') as file:
    file.write('Hello, World!')

# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
        

Reading and Writing Binary Files

Binary files can be handled by adding 'b' to the mode string in the open function. This is useful for non-text files such as images, audio files, and executable files.


# Writing binary data to a file
with open('example.bin', 'wb') as file:
    file.write(b'\x00\x01\x02\x03')

# Reading binary data from a file
with open('example.bin', 'rb') as file:
    data = file.read()
    print(data)
        

Working with File Paths

The os.path and pathlib modules provide functions for manipulating file paths. These modules help to construct paths in a way that is independent of the operating system.


import os
from pathlib import Path

# Using os.path
# Joining paths
path = os.path.join('folder', 'file.txt')
print(path)  # Output will depend on the OS

# Getting the file extension
extension = os.path.splitext(path)[1]
print(extension)

# Using pathlib
path = Path('folder') / 'file.txt'
print(path)  # Output will depend on the OS

# Getting the file extension
extension = path.suffix
print(extension)
        

Handling I/O Errors

Always handle I/O errors gracefully to prevent your program from crashing. Common errors include FileNotFoundError, PermissionError, and IOError. Using try-except blocks helps to handle these errors effectively.


try:
    with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    content = 'File not found.'
except PermissionError:
    content = 'Permission denied.'
print(content)
        

Appending to Files

You can append data to an existing file using the 'a' mode in the open function. This is useful for logging and other applications where you need to keep adding data to a file without overwriting its current contents.


# Appending to a file
with open('example.txt', 'a') as file:
    file.write('\nAppend this line.')

# Reading the appended file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
        

Prompting Generative AI for Effective File Handling and I/O

By providing a well-crafted prompt, you can obtain AI-generated code that meets specific criteria or solves a particular problem.

Example Prompt:
Generate a Python script that reads a CSV file, processes the data, and writes the results to a new CSV file, handling any file-related errors gracefully.

Resulting AI-generated code:


import csv

def process_csv(input_file, output_file):
    try:
        with open(input_file, 'r') as infile:
            reader = csv.reader(infile)
            data = [row for row in reader]

        # Process data (example: convert all text to uppercase)
        processed_data = [[cell.upper() for cell in row] for row in data]

        with open(output_file, 'w', newline='') as outfile:
            writer = csv.writer(outfile)
            writer.writerows(processed_data)
        return "Processing complete."
    except FileNotFoundError:
        return "Input file not found."
    except PermissionError:
        return "Permission denied."
    except Exception as e:
        return f"An error occurred: {str(e)}"

result = process_csv('input.csv', 'output.csv')
print(result)
        
Back to Home