How to correctly work with external text files

108 Views Asked by At

Could someone please help with the correct way or there opinion on this. I have written code which is below that is supposed to take input from a text file arrange one line in order and state which is the minimum number then the same on the next line for the maximum number and finally for the average of all numbers.

My code:

from statistics import mean
def number1():
    with open('input.txt') as file:
    data = {line.split(':')[0]: sorted([int(value) for value in line.split(':')[1].split(',')]) for line in file.readlines()}
    functions = {'min': min, 'max': max, 'avg': mean}
with open('output.txt', 'w') as file:
     file.writelines(f"The {function} of {values} is {functions[function](values)}\n" for function, values in data.items())
number1()

I was told this was incorrect. Below is the code suggested that I should use but after clearing the indentation which I think is correct. I only get an output of the average line.

Suggested code:

outfile = open("output.txt", "w")

with open("input.txt") as f:
    for line in f:
        # clean line and split into operator and data
        operator, data = line.lower().strip().split(":")

    line = line.split(":")
    operator = line[0].lower().strip()
    data = line[1].strip().split(",")

        # parse data into list of integers
        # data = [int(x) for x in data.split(",")]
        # convert numbers in list to integer
    newData = []

    for x in data:
          newData.append(int(x))

        # min(), max(), sum(), len()
        # determine operation to perform on number list variable
    if operator == "min":
            result = min(newData)
    elif operator == "max":
            result = max(newData)
    elif operator == "avg":
            result = sum(newData) / len(newData)

        # create output string
    report_line = "The {} of {} is {}.\n".format(operator, newData, result)
    outfile.write(report_line)
outfile.close()        
1

There are 1 best solutions below

2
On

You can use below logic.

Say your text file is data.txt with below content

3 7 5 
0 4 2 
8 1 6 

2 6 3 
1 0 8 
5 4 7 

4 1 6 
0 8 7 
2 3 5 

7 2 6 
4 1 3 
8 0 5 

Use the below code to insert all the number into list and find min and max.

list = []
file = open('data.txt', 'r')
for line in file.readlines():
    for n in line:
        if (n!=" " and  n!="\n"):
            list.append(n)
print(list)
print(min(list),max(list))