Python - Reading and Writing Files

17.
How do you handle exceptions when reading or writing files?

When reading or writing files in Python, it's important to handle exceptions to gracefully manage errors that may occur during file operations. Common exceptions include FileNotFoundError, PermissionError, and IOError. Using a try-except block allows you to catch and handle these exceptions, providing a way to respond to errors and prevent program crashes.

file_path = 'nonexistent_file.txt'

# Example of handling FileNotFoundError when reading a file
try:
    with open(file_path, 'r') as file:
        content = file.read()
        print("File Content:")
        print(content)
except FileNotFoundError:
    print(f"The file '{file_path}' does not exist.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
file_path = 'read-only-file.txt'

# Example of handling PermissionError when writing to a file
try:
    with open(file_path, 'w') as file:
        file.write("This is a write operation.")
except PermissionError:
    print(f"Permission error: Unable to write to the file '{file_path}'.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

In these examples, a try-except block is used to catch specific exceptions that may occur during file operations. The program responds to each exception appropriately, printing a custom error message. The Exception class is a general catch-all for unexpected errors.

The outputs of the programs will depend on the specific errors encountered, and the custom error messages will be displayed accordingly.


18.
What is the purpose of the flush() method in file handling?

The flush() method in Python is used to flush the internal buffer of a file. When you write data to a file, it is often buffered, meaning that the data is not immediately written to the file on the disk. The flush() method forces the buffered data to be written to the file.

Here's an example program that demonstrates the purpose of the flush() method:

file_path = 'flush_example.txt'

# Open the file in write mode
with open(file_path, 'w') as file:
    # Write content to the file without flushing
    file.write("This is some data without flushing.")

    # Use flush() to force the data to be written to the file
    file.flush()

    # Write more content to the file
    file.write("This data is written after flushing.")

# Read the contents of the written file
with open(file_path, 'r') as read_file:
    content = read_file.read()
    print("File Content:")
    print(content)

In this example, the file 'flush_example.txt' is opened in write mode using the with statement. Two sets of data are written to the file, but the flush() method is used after the first set to force the buffered data to be written immediately. Without the flush() method, the data might be held in the buffer until the file is closed or until the buffer is full.

The output of the program will be:

File Content:
This is some data without flushing.This data is written after flushing.

19.
Discuss the use of the truncate() method in file handling.

The truncate() method in Python is used to resize a file to a specified size. If the specified size is smaller than the current size of the file, the extra data at the end of the file is removed. If the specified size is larger, the file is extended, and the new space is filled with null bytes.

Here's an example program that demonstrates the use of the truncate() method:

file_path = 'truncate_example.txt'

# Open the file in write mode
with open(file_path, 'w') as file:
    # Write initial content to the file
    file.write("This is some initial data.")

# Read and print the contents of the file before truncating
with open(file_path, 'r') as read_file:
    content_before = read_file.read()
    print("File Content Before Truncating:")
    print(content_before)

# Open the file in read+write mode
with open(file_path, 'r+') as file:
    # Move the file pointer to a specific position (optional)
    file.seek(10)

    # Truncate the file at the current position (or provide a size)
    file.truncate()

# Read and print the contents of the file after truncating
with open(file_path, 'r') as read_file:
    content_after = read_file.read()
    print("File Content After Truncating:")
    print(content_after)

In this example, the file 'truncate_example.txt' is opened in write mode to write initial content. The current content of the file is then read and printed. Later, the file is opened in read+write mode, the file pointer is moved to a specific position (optional), and the truncate() method is used to truncate the file at the current position. Finally, the content of the file after truncating is read and printed.

The output of the program will be:

File Content Before Truncating:
This is some initial data.
File Content After Truncating:
This is some

20.
How can you read and write CSV files in Python?

To read and write CSV files in Python, you can use the built-in csv module. The csv module provides functions to read from and write to CSV files. Here's an example program that demonstrates reading and writing CSV files:

import csv

# Example data for writing to a CSV file
data_to_write = [
    ['Name', 'Age', 'City'],
    ['Alice', 28, 'New York'],
    ['Bob', 35, 'San Francisco'],
    ['Charlie', 22, 'Los Angeles']
]

# Writing data to a CSV file
csv_file_path = 'example.csv'
with open(csv_file_path, 'w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerows(data_to_write)

# Reading data from a CSV file
with open(csv_file_path, 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    
    # Skip the header row if present
    header = next(csv_reader, None)
    if header:
        print("CSV Header:", header)
    
    # Print the remaining rows
    print("CSV Content:")
    for row in csv_reader:
        print(row)

In this example, the program writes data to a CSV file using the csv.writer object, and then reads the data back from the CSV file using the csv.reader object. The newline='' parameter is used to ensure consistent line endings when writing CSV files.

The output of the program will be:

CSV Header: ['Name', 'Age', 'City']
CSV Content:
['Alice', '28', 'New York']
['Bob', '35', 'San Francisco']
['Charlie', '22', 'Los Angeles']