# -*- coding: utf-8 -*-
"""
================================================================================
Comprehensive Python Guide: File Handling
================================================================================
This program provides an in-depth demonstration of how to perform file
input/output (I/O) operations in Python. It covers creating, writing to,
appending to, and reading from files.
The 'with' statement is used throughout, as it is the recommended best
practice for handling file objects, ensuring they are automatically and
safely closed even if errors occur.
Sections:
1. Writing to a File ('w' mode) - Overwrites existing content.
2. Appending to a File ('a' mode) - Adds content to the end.
3. Reading from a File ('r' mode) - Various reading techniques.
4. Error Handling for File Operations.
"""
import os # We'll use the os module to clean up the file at the end.
# A function to print section headers for better readability.
def print_header(title):
"""Prints a formatted header to the console."""
print("\n" + "="*60)
print(f"| {title.center(56)} |")
print("="*60)
# Define the filename we will use for all operations.
FILENAME = "demo_file.txt"
# ==============================================================================
# SECTION 1: WRITING TO A FILE ('w' mode)
# ==============================================================================
# The 'w' mode opens a file for writing.
# WARNING: If the file already exists, its contents are completely erased.
# If the file does not exist, it will be created.
print_header("1. Writing to a File ('w' mode)")
try:
# The 'with' statement handles opening and closing the file.
with open(FILENAME, 'w') as f:
print(f"File '{FILENAME}' opened in write mode ('w').")
f.write("Hello, World!\n")
f.write("This is the first line written to the file.\n")
lines_to_write = [
"Here is another line.\n",
"And a final one for this section.\n"
]
f.writelines(lines_to_write) # writelines() writes a list of strings
print("Successfully wrote initial content to the file.")
except IOError as e:
print(f"An error occurred during writing: {e}")
# ==============================================================================
# SECTION 2: APPENDING TO A FILE ('a' mode)
# ==============================================================================
# The 'a' mode opens a file for appending.
# New data is added to the end of the file.
# If the file does not exist, it will be created.
print_header("2. Appending to a File ('a' mode)")
try:
with open(FILENAME, 'a') as f:
print(f"File '{FILENAME}' opened in append mode ('a').")
f.write("\n--- Appended Content ---\n")
f.write("This line was added later without erasing the original content.\n")
print("Successfully appended new content to the file.")
except IOError as e:
print(f"An error occurred during appending: {e}")
# ==============================================================================
# SECTION 3: READING FROM A FILE ('r' mode)
# ==============================================================================
# The 'r' mode opens a file for reading. This is the default mode.
print_header("3. Reading from a File ('r' mode)")
try:
print(f"File '{FILENAME}' opened in read mode ('r').")
# --- 3.1: Reading the entire file at once ---
print("\n--- 3.1: Reading the entire file with read() ---")
with open(FILENAME, 'r') as f:
full_content = f.read()
print("--- File Content Start ---")
print(full_content)
print("--- File Content End ---")
# --- 3.2: Reading the file line by line ---
print("\n--- 3.2: Reading line by line with a for loop ---")
with open(FILENAME, 'r') as f:
print("--- File Content Start ---")
for line in f:
# The print function adds its own newline, so we use strip()
# to remove the newline character from the end of the line.
print(line.strip())
print("--- File Content End ---")
# --- 3.3: Reading all lines into a list ---
print("\n--- 3.3: Reading all lines into a list with readlines() ---")
with open(FILENAME, 'r') as f:
all_lines = f.readlines() # Returns a list of strings
print(f"The file content as a list of lines:\n{all_lines}")
# You can then process this list
print(f"The second line in the file was: '{all_lines[1].strip()}'")
except IOError as e:
print(f"An error occurred during reading: {e}")
# ==============================================================================
# SECTION 4: ERROR HANDLING FOR FILE OPERATIONS
# ==============================================================================
print_header("4. Error Handling")
# --- 4.1: Handling a non-existent file ---
print("\n--- 4.1: Trying to read a file that does not exist ---")
try:
with open("non_existent_file.txt", 'r') as f:
content = f.read()
print(content)
except FileNotFoundError:
print("Caught the error: The file 'non_existent_file.txt' was not found.")
except Exception as e:
# A general catch-all for other potential errors
print(f"An unexpected error occurred: {e}")
# ==============================================================================
# CLEANUP
# ==============================================================================
# This part is just to keep our directory clean after running the demo.
if os.path.exists(FILENAME):
os.remove(FILENAME)
print(f"\nCleanup: Removed the demo file '{FILENAME}'.")
print("\n" + "="*60)
print("DEMONSTRATION COMPLETE".center(60))
print("="*60)