""" File Handling and Exception Handling Example in Python
This script demonstrates basic file reading and writing operations along with robust exception handling for common file-related issues.
It reads data from an input file (specified by the user or a default), processes each line (in this example, it just prints it), and writes a summary to an output file. It includes error handling for file not found, permission errors, and other potential I/O exceptions. """
import sys
def read_file_content(filepath): """ Reads the content of a file line by line and returns a list of lines. Handles FileNotFoundError. """ try: with open(filepath, 'r') as file: lines = file.readlines() return lines except FileNotFoundError: print(f"Error: Input file '{filepath}' not found.") return None except IOError as e: print(f"Error reading file '{filepath}': {e}") return None
def process_line(line): """ Processes a single line of text (in this example, it just returns it). You can add more complex processing logic here. """ return line.strip()
def write_summary_to_file(filepath, summary_lines): """ Writes a list of lines to a specified output file. Handles IOError. """ try: with open(filepath, 'w') as file: file.writelines(summary_lines) print(f"Summary written to '{filepath}' successfully.") except IOError as e: print(f"Error writing to file '{filepath}': {e}")
def main(): """ Main function to handle file reading, processing, and writing. """ input_file = "input.txt" # Default input file output_file = "output_summary.txt"
if len(sys.argv) > 1:
input_file = sys.argv[1]
if len(sys.argv) > 2:
output_file = sys.argv[2]
print(f"Reading from: {input_file}")
print(f"Writing summary to: {output_file}")
lines = read_file_content(input_file)
if lines is not None:
processed_data = []
for line in lines:
processed_line = process_line(line)
print(f"Processed line: {processed_line}")
processed_data.append(f"Processed: {processed_line}\n")
write_summary_to_file(output_file, processed_data)
else:
print("No data was processed due to input file errors.")
if name == "main": # Create a sample input file for testing try: with open("input.txt", "w") as f: f.write("This is the first line.\n") f.write("Another line of text.\n") f.write("End of file.\n") print("Sample 'input.txt' created.") except IOError as e: print(f"Error creating sample input file: {e}")
main()
