Module 5: Files, Exceptions, and Errors in Python
Problem Statement: Write a Python program that:
- Opens and reads a text file named sample.txt.
- Prints its content line by line.
- Handles errors gracefully if the file does not exist.
try:
# Attempt to open the file
file = open("sample.txt", "r")
- This tries to open the file named
sample.txt
in read mode ("r"
). - If the file doesn't exist, it raises a
FileNotFoundError
, which will be caught in theexcept
block.
print("File contents:\n")
line_count = 1
- This prints a header before the file content.
- Initializes a variable
line_count
to keep track of line numbers while reading.
# Read line by line
for line in file:
print(f"Line {line_count} : ", line.strip())
line_count += 1
- A loop that reads the file line by line.
line.strip()
removes any leading/trailing whitespace (like\n
).print(f"Line {line_count} : ", ...)
shows the current line number along with its content.line_count += 1
increments the line counter after each line.
except FileNotFoundError:
# Handle the case where the file doesn't exist
print("Error: The file 'sample.txt' does not exist.")
- If the file is not found, this block catches the error and prints an error message instead of crashing the program.
File contents:
Line 1 : This is a test file.
Line 2 : It has several lines.
Line 3 : End of file.
Error: The file 'sample.txt' does not exist.
Problem Statement: Write a Python program that:
- Takes user input and writes it to a file named output.txt.
- Appends additional data to the same file.
- Reads and displays the final content of the file.
filename = "output.txt"
user_input = input("Enter text to write to the file : ")
- Defines the file name as
"output.txt"
. - Takes user input to write to the file initially.
output_file = open(filename, "w")
write_in_file = output_file.write(user_input + "\n")
output_file.close()
- Opens the file in write mode (
"w"
), which overwrites the file if it already exists. - Writes the user input followed by a newline (
\n
) to the file. - Closes the file to save changes.
print("Data successfully written to ", filename)
- Confirms that data was written.
output_file1 = open(filename, "a")
user_input1 = input("Enter text to write to the file : ")
write_in_file1 = output_file1.write(user_input1)
output_file1.close()
- Reopens the file in append mode (
"a"
), which adds new content to the end without deleting previous data. - Takes a second user input and writes it.
- Closes the file.
print(write_in_file1)
- Prints the number of characters written to the file from the second input.
print("Final content of ", filename)
- Displays the file name whose content is about to be printed.
try:
# Attempt to open the file
file = open(filename, "r")
# Read line by line
for line in file:
print(line.strip())
- Tries to open the file in read mode (
"r"
). - Reads and prints each line with leading/trailing whitespace removed using
.strip()
.
except FileNotFoundError:
print("Error: The file 'output.txt' does not exist.")
- If the file is not found, this prints an error message instead of crashing the program.
Enter text to write to the file : Hello
Data successfully written to output.txt
Enter text to write to the file : World
5
Final content of output.txt
Hello
World