blog image

Python Files and Exception solution

February 16, 20248 min read

Problem 1: File Reading in Python

Problem Statement:

You are tasked with writing a Python script to read the contents of a text file named sample.txt and display them on the screen. The file contains a list of names, each on a new line. Your program should also count the number of names in the file and print this count at the end.

Solution:

# Open the file in read mode
with open('sample.txt', 'r') as file:
    # Read all lines in the file
    lines = file.readlines()
    # Print each line (name)
    for line in lines:
        print(line.strip())  # strip() removes any leading/trailing whitespace
    
    # Print the count of names
    print(f"Total names in the file: {len(lines)}")

Example Input (sample.txt):

Alice
Bob
Charlie
Diana

Example Output:

Alice
Bob
Charlie
Diana
Total names in the file: 4

Problem 2: File Writing in Python

Problem Statement:

Create a Python program that takes a list of student scores, writes them to a file named scores.txt, with each score on a new line. Then, calculate the average score and append this information at the end of the file.

Solution:

scores = [95, 78, 88, 92, 67]

# Write scores to the file
with open('scores.txt', 'w') as file:
    for score in scores:
        file.write(f"{score}\n")

# Calculate average score
average_score = sum(scores) / len(scores)

# Append average score to the file
with open('scores.txt', 'a') as file:
    file.write(f"Average Score: {average_score}\n")

Example Output (scores.txt):

95
78
88
92
67
Average Score: 84.0

Problem 3: File Content Reversal

Problem Statement:

Write a Python script to reverse the contents of a text file named story.txt and save the reversed content into a new file named reversed_story.txt. The script should reverse the order of the lines, not the text within each line.

Solution:

# Read the contents of the original file
with open('story.txt', 'r') as file:
    lines = file.readlines()

# Reverse the order of the lines
reversed_lines = lines[::-1]

# Write the reversed content to a new file
with open('reversed_story.txt', 'w') as new_file:
    new_file.writelines(reversed_lines)

Example Input (story.txt):

Once upon a time,
there was a brave knight,
who fought dragons.

Example Output (reversed_story.txt):

who fought dragons.
there was a brave knight,
Once upon a time,

Problem 4: Line Number Addition

Problem Statement:

Develop a Python program that reads a text file named input.txt and creates a new file named numbered_input.txt where each line from the original file is prefixed with its line number followed by a colon.

Solution:

# Read the original file and write to a new file with line numbers
with open('input.txt', 'r') as file, open('numbered_input.txt', 'w') as new_file:
    lines = file.readlines()
    for i, line in enumerate(lines, start=1):
        new_file.write(f"{i}: {line}")

Example Input (input.txt):

Hello, World!
This is a test file.
Python programming is fun.

Example Output (numbered_input.txt):

1: Hello, World!
2: This is a test file.
3: Python programming is fun.

Problem 5: Unique Words Counter

Problem Statement:

Create a Python script that reads a text file named essay.txt, counts the unique words in the file, and writes the count to a new file named unique_words_count.txt. Words are considered the same if they are case-insensitive matches.

Solution:

# Read the content of the essay
with open('essay.txt', 'r') as file:
    text = file.read().lower()  # Convert text to lowercase to ensure case-insensitive matching
    words = text.split()

# Count unique words
unique_words = set(words)  # Set to get unique words
count = len(unique_words)

# Write the count to a new file
with open('unique_words_count.txt', 'w') as new_file:
    new_file.write(f"Unique words count: {count}\n")

Example Input (essay.txt):

Python is great. Python is easy. Python is powerful.

Example Output (unique_words_count.txt):

Unique words count: 5

Problem 6: Dividing Numbers

Question: Write a Python program that asks the user to input two numbers and then divides the first number by the second number. Your program should handle cases where the user might input a value that causes a division by zero error (ZeroDivisionError).

Example:

  • If the user inputs 8 and 0, the program should print "Cannot divide by zero!" instead of crashing.

  • Expected output for inputs 8 and 2 should be 4.0.

Solution:

try:
    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    result = num1 / num2
    print("The result is:", result)
except ZeroDivisionError:
    print("Cannot divide by zero!")

This solution uses a try block to attempt the division operation and an except block to catch the ZeroDivisionError. If the error occurs, it prints a friendly message instead of terminating the program abruptly.

Problem 7: Converting Input to Numbers

Question: Create a Python script that prompts the user to enter a number and then prints the square of that number. Use exception handling to catch cases where the input cannot be converted to a number (ValueError).

Example:

  • If the user inputs "a", the program should print "Please enter a valid number." instead of crashing.

  • Expected output for input 4 should be 16.

Solution:

try:
    num = float(input("Enter a number: "))
    print("The square of the number is:", num**2)
except ValueError:
    print("Please enter a valid number.")

Here, the try block attempts to convert the input to a float and calculates its square. The except block catches a ValueError if the conversion fails, providing a clear message to the user.

Problem 8: Accessing List Elements

Question: Suppose you have a list of numbers, for example, numbers = [1, 2, 3, 4, 5]. Write a program that asks the user for an index and prints the element at that index in the list. Your program should handle cases where the user requests an index out of the list's bounds (IndexError).

Example:

  • If the user inputs 10, the program should print "Index is out of bounds!" since there is no element at index 10.

  • Expected output for input 2 should be 3.

Solution:

numbers = [1, 2, 3, 4, 5]
try:
    index = int(input("Enter an index: "))
    print("The element at index", index, "is:", numbers[index])
except IndexError:
    print("Index is out of bounds!")
except ValueError:
    print("Please enter a valid integer.")

This solution includes two except blocks: one for an IndexError if the user enters an index that is out of range, and another for a ValueError if the user doesn't input an integer. It demonstrates handling multiple types of exceptions in a single try-except statement.

Problem 9: File Reading

Question: Write a Python program to open a file named "data.txt" and print its contents to the console. Use exception handling to catch and handle the case where the file does not exist (FileNotFoundError).

Example:

  • If "data.txt" does not exist in the program's directory, the program should print "File not found!" instead of crashing.

  • If "data.txt" exists and contains "Hello, world!", the program should print "Hello, world!".

Solution:

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found!")

This solution uses a try block to attempt to open and read the file, and an except block to catch the FileNotFoundError. It provides a friendly message to the user instead of terminating the program with an error.

Problem 10: Multiple Number Conversion

Question: Create a Python program that converts a list of strings into integers. The list is ["10", "20", "hello", "40"]. Use exception handling to skip over any values that cannot be converted to an integer and print the rest as integers.

Example:

  • Given the list ["10", "20", "hello", "40"], the program should print:

10
20
Cannot convert 'hello' to an integer.
40

Solution:

strings = ["10", "20", "hello", "40"]
for s in strings:
    try:
        print(int(s))
    except ValueError:
        print(f"Cannot convert '{s}' to an integer.")

This solution iterates over each string in the list, attempting to convert it to an integer inside a try block. If a ValueError is raised during conversion, the except block catches it and prints a message indicating the failure.

Problem 11: Division with User Input Validation

Question: Modify the division program from Problem 6 to include handling for non-numeric inputs. The program should ask the user for two numbers and divide the first by the second, handling both division by zero and non-numeric inputs.

Example:

  • If the user inputs 9 and three, the program should print "Please enter only numbers." instead of crashing.

  • Expected output for inputs 9 and 3 should be 3.0.

Solution:

try:
    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    result = num1 / num2
    print("The result is:", result)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Please enter only numbers.")

This solution adds an additional except block for ValueError to catch cases where the input cannot be converted to a float, alongside handling ZeroDivisionError.

Problem 12: Dictionary Key Access

Question: Write a Python script that accesses a value in a dictionary using a key provided by the user. Use a dictionary like data = {"name": "John", "age": 30}. Your program should handle the case where the key does not exist in the dictionary (KeyError).

Example:

  • If the user inputs occupation, the program should print "Key not found!" since there is no occupation key in the dictionary.

  • Expected output for input name should be John.

Solution:

data = {"name": "John", "age": 30}
try:
    key = input("Enter a key: ")
    print(f"The value is: {data[key]}")
except KeyError:
    print("Key not found!")

This solution uses a try block to attempt to access the dictionary value using the user-provided key and an except block to catch a KeyError if the key is not found in the dictionary, providing a clear and friendly message.

blog author image

sunil s

Quant Developer & Mentor

Back to Blog