Home > Software design >  Read data from txt file, store it, use it for analyzing, write it to the txt file
Read data from txt file, store it, use it for analyzing, write it to the txt file

Time:11-07

The task is to read from given txt file the data add the numbers in there to the list[], so that every number in a row will be a element/object in this list. After reading the file created list will be sent to the main(). this list with the objects will be parameters for the def Analyze part in where at the same time will be found min, max, average and sum. txt file

def lueTiedosto(data):
    Tiedosto = open("L07T4D1.txt", 'r', encoding="UTF-8")
    Rivi = Tiedosto.readline()
    while (len(Rivi) > 0):
        data.append(int(Rivi))
        Rivi = Tiedosto.readline()
    for element in data:
        print(element)
    print(f"Tiedosto L07T4D1.txt luettu.")
    Tiedosto.close()
    return element

The fixed code which works:

def lueTiedosto(data):
    Lue = input("Luettavan tiedoston nimi on ''.\n")
    print(f"Anna uusi nimi, enter säilyttää nykyisen: ", end='')
    Tiedosto = open(Lue, 'r', encoding="UTF-8")
    Rivi = Tiedosto.readline()
    while (len(Rivi) > 0):
        data.append(int(Rivi))
        Rivi = Tiedosto.readline()
    print(f"Tiedosto '{Lue}' luettu.")
    Tiedosto.close()
    return data

CodePudding user response:

Making an assumption that your input file is similar to the following:

10000
12345 
10008
12000

I would do the following:

filepath = r".......\L07T4D1.txt"  # Path to file being loaded

def readData(filepath: str) -> list[int]:
    # Returns a list of integers from file
    rslt = []
    with open (filepath, 'r') as f:
        data = f.readline().strip()
        while data:
            data = data.split(' ')
            rslt.append(int(data[0]))
            data = f.readline().strip()
    return rslt   

def analyze(data: list[int]) -> None:
    # prints results of data analysis
    print(f'Max Value = {max(data)}')
    print(f'Min Value = {min(data)}')
    print(f'Sum Value = {sum(data)}')
    print(f'Avg Value = {sum(data)/len(data)}') 

Running analyze(readData(filepath)) Yields:

Max Value = 12345
Min Value = 10000
Sum Value = 44353
Avg Value = 11088.25
  • Related