Implement the function `fileSum`, which takes the name of a file as an argument. The function should open the file, sum all the integers contained in it, close the file, and return the sum. If the file does not exist, the function should display an error message and call the `exit` function to terminate the program with an error code of `1`.

Answered on

To implement the `fileSum` function in Python, follow the given steps:

1. Open the file using a `with` block, so the file will be closed automatically after the block is executed.

2. Read the file line by line, convert each line to an integer, and add it to the sum.

3. Handle the case where the file does not exist using a `try...except` block.

4. If the file does not exist, print the error message and exit the program with an error code of `1`.

Here is a Python function that demonstrates this logic:

```python import sys

def fileSum(filename): try: with open(filename, 'r') as file: total_sum = 0 for line in file: total_sum += int(line) return total_sum except FileNotFoundError: print(f"Error: The file {filename} does not exist.") sys.exit(1)

Example usage: # Assuming the file 'numbers.txt' exists and contains integers, one on each line: # sum_of_numbers = fileSum('numbers.txt') # print(sum_of_numbers) ```

Related Questions