DEV Community

FaithInErrorsZORO
FaithInErrorsZORO

Posted on

Reading and writing with files in python?

def sum_column(filename):
total, error_count = 0, 0
with open(filename, 'r') as file:
for line in file:
try:
total += int(line.strip())
except ValueError:
error_count += 1
return total, error_count

def sum_all(filename):
total, error_count = 0, 0
with open(filename, 'r') as file:
for line in file:
for num in line.split():
try:
total += int(num)
except ValueError:
error_count += 1
return total, error_count

def main():
filename = input("Enter a file name: ")
operation = input("Enter operation (sum_column or sum_all): ")

try:
    if operation == "sum_column":
        result, errors = sum_column(filename)
        print(f"Sum: {result}, Errors: {errors}")
    elif operation == "sum_all":
        result, errors = sum_all(filename)
        print(f"Sum: {result}, Errors: {errors}")
    else:
        print("Invalid operation entered.")
except FileNotFoundError:
    print(f"User-friendly message: The file '{filename}' does not exist.")
Enter fullscreen mode Exit fullscreen mode

if name == "main":
main()

Top comments (0)