Solution on Files & Exception

October 9, 2025

đź§© Problem 1: Read and Display File Content

Description:
Write a Python program to open a text file named info.txt and display its contents.
If the file does not exist, display a custom message like “File not found.”

Solution:

try:
    file = open("info.txt", "r")
    content = file.read()
    print(content)
    file.close()
except FileNotFoundError:
    print("File not found. Please check the filename.")

Explanation:
The program attempts to open info.txt in read mode.
If it doesn’t exist, Python raises a FileNotFoundError, which we catch and handle gracefully.


đź§© Problem 2: Write User Input to a File

Description:
Ask the user to input a few lines of text and write them to a file called user_notes.txt.

Solution:

file = open("user_notes.txt", "w")
while True:
    line = input("Enter text (or 'exit' to stop): ")
    if line.lower() == 'exit':
        break
    file.write(line + "\n")
file.close()
print("Data successfully written to user_notes.txt")

Explanation:
The program takes multiple lines from the user and writes each to a file.
It stops when the user types 'exit'.


đź§© Problem 3: Append Data to a File

Description:
Append a new line "New data added successfully." to an existing file log.txt.
If the file doesn’t exist, create it.

Solution:

file = open("log.txt", "a")
file.write("\nNew data added successfully.")
file.close()
print("Data appended successfully.")

Explanation:
Using append mode "a", data is added to the end of the file without overwriting it.
If the file doesn’t exist, Python automatically creates it.


đź§© Problem 4: Count Number of Lines in a File

Description:
Count and display the total number of lines in data.txt.

Solution:

try:
    count = 0
    with open("data.txt", "r") as file:
        for line in file:
            count += 1
    print("Total number of lines:", count)
except FileNotFoundError:
    print("File not found.")

Explanation:
Each iteration over the file counts one line.
Using with ensures the file is closed automatically.


đź§© Problem 5: Copy Content from One File to Another

Description:
Copy all content from source.txt to destination.txt.
Handle the error if the source file doesn’t exist.

Solution:

try:
    with open("source.txt", "r") as src:
        data = src.read()
    with open("destination.txt", "w") as dest:
        dest.write(data)
    print("File copied successfully!")
except FileNotFoundError:
    print("source.txt not found.")

Explanation:
The with statement handles both reading and writing safely.
If source.txt doesn’t exist, the program prints an error instead of crashing.


đź§© Problem 6: Count Words in a File

Description:
Count the total number of words in story.txt.

Solution:

try:
    with open("story.txt", "r") as file:
        text = file.read()
        words = text.split()
        print("Total words:", len(words))
except FileNotFoundError:
    print("File not found.")

Explanation:
split() divides the text into words by whitespace.
We count them using len().


đź§© Problem 7: Read File Using with Statement

Description:
Use the with statement to read example.txt line by line.

Solution:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())

Explanation:
The with statement automatically closes the file.
strip() removes newline characters for clean output.


đź§© Problem 8: Handle Division Error from File Input

Description:
You have a file numbers.txt containing two numbers (one per line).
Read them and divide the first by the second.
Handle division by zero properly.

Solution:

try:
    with open("numbers.txt", "r") as file:
        num1 = int(file.readline())
        num2 = int(file.readline())
        print("Result:", num1 / num2)
except FileNotFoundError:
    print("numbers.txt not found.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Explanation:
We read two integers from the file.
If the second number is zero, we catch the ZeroDivisionError.


© Copyright 2025 — Fessorpro

Terms of Service / Privacy Policy