Problems 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 on the screen.
If the file does not exist, display a custom message like “File not found.”

Concepts Covered:

  • File reading using open()
  • Handling FileNotFoundError

Example:

File content:
Hello, Python learners!
Welcome to file handling.


đź§© 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.
Each input line should be written on a new line.

Concepts Covered:

  • Writing files with "w" mode
  • Taking user input and writing multiple lines

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

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

Concepts Covered:

  • Using "a" mode for appending
  • Creating file if it doesn’t exist

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

Description:
Write a Python script to count and display the total number of lines in data.txt.

Concepts Covered:

  • Iterating over file lines
  • Counting items using loops

Example:

If data.txt contains:
Line 1
Line 2
Line 3

Output: 3 lines


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

Description:
Create a program that copies all content from source.txt to destination.txt.
If source.txt doesn’t exist, handle the error properly.

Concepts Covered:

  • Reading and writing files
  • Using try...except for file handling

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

Description:
Write a program to count the number of words in story.txt.
Display the total word count to the user.

Concepts Covered:

  • File reading
  • String splitting and counting

Example:

File content: "Python makes file handling easy."
Output: 5 words


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

Description:
Open a file example.txt using the with statement and display its contents line by line.
Demonstrate how Python automatically closes the file afterward.

Concepts Covered:

  • with open() context manager
  • Automatic file closing

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

Description:
You have a file numbers.txt containing two numbers (one per line).
Read the numbers and divide the first by the second.
If the second number is zero, display “Cannot divide by zero.”

Concepts Covered:

  • Reading numbers from a file
  • Handling ZeroDivisionError

© Copyright 2025 — Fessorpro

Terms of Service / Privacy Policy