My issue
Coding problem - 2
The code given in the IDE intends to read numbers from an input file named “numbers.txt” and calculate their sum.
However, the file handling code is incomplete and needs to be fixed.
Complete the code to solve the problem.
Clue: Check the numbers.txt file stored in the /mnt/codechef/ directory.
My code
def calculate_sum_from_file(filename):
total_sum = 0
try:
with open(filename, 'r') as file:
# Read all lines from the file
lines = file.readlines()
# Process each line
for line in lines:
# Split the line into individual numbers (assuming space-separated)
numbers = line.split()
# Convert each number to integer and sum them up
for number in numbers:
total_sum += int(number)
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"Error: {e}")
return total_sum
# Example usage:
file_path = '/mnt/codechef/numbers.txt'
total_sum = calculate_sum_from_file(file_path)
print(f"Sum of numbers in '{file_path}': {total_sum}")
Learning course: Python Programming
Problem Link: Coding problem - 2 in Python Programming