This project is a beginner-friendly introduction to file handling and exception handling in Python. It includes two scripts that cover the fundamental concepts required for reading, writing, and safely managing files.
This assignment is divided into two parts:
- File Read & Write Challenge: A script that reads text from an input file, modifies it, and saves it to an output file.
- Error Handling Lab: A script that demonstrates how to handle errors gracefully when a requested file does not exist.
This assignment focuses on the following beginner-level Python concepts:
- File Handling:
open(filename, mode)
: To open a file with a specific mode ('r'
for reading,'w'
for writing)..read()
: To read the entire content of a file..write()
: To write content to a file.with
statement: To ensure that files are automatically closed after use, which is a best practice.
- Exception Handling:
try-except
block: To catch and handle potential errors without crashing the program.FileNotFoundError
: To specifically handle cases where a file does not exist.finally
: To execute cleanup code regardless of whether an error occurred.
This script demonstrates how to read from one file and write to another.
- Make sure you have a file named
input.txt
in the same directory. - Run the script from your terminal:
python3 file_operations.py
The script will create a new file named output.txt
containing the uppercase version of the text from input.txt
. You will see the following message in your terminal:
File operations completed successfully!
Original content from 'input.txt' has been modified and saved to 'output.txt'.
This script shows how to handle errors safely, particularly when a file might not be found.
- Run the script from your terminal:
python3 error_handling.py
- The script will prompt you to enter a filename.
-
If you enter an existing filename (e.g.,
input.txt
): The script will display the contents of the file.Please enter the filename to read: input.txt --- File Content --- This is the original content of the file. It has multiple lines. We will read this file and modify its content. -------------------- File reading process finished.
-
If you enter a non-existent filename (e.g.,
nonexistent.txt
): The script will show a friendly error message instead of crashing.Please enter the filename to read: nonexistent.txt Error: The file 'nonexistent.txt' was not found. Please make sure the file exists and you have entered the correct name. File reading process finished.