Search code examples
pythonloopsread-write

Why does it seem like only the last line is being read in the text file?


I'm quite new to this so do excuse any newbie errors.

So the goal of my code is to use the 3 lines of data in a text file ("Numbers.txt") to carry out some calculations line by line. I then want to write the results of these calculations into a new text file ("Newnumbers.txt").

The "Numbers.txt" file contains the following 3 lines of data:

1, 2, 3, 4, 5, 6, 7
2, 4, 6, 8, 10, 12, 14
1, 3, 5, 7, 9, 11, 13

Whenever I run this code, only the last line seems to be read. The "calcresults" prints as [2, 4, 14, 2, 4, 14, 2, 4, 14].

Where am I going wrong? I'd very much appreciate any help :)

Here's my script:

numbers = open("Numbers.txt", "r")

for line in numbers:
    (m, a, e, i, o, O, E) = line.split(",")
    print(line)
    m = int(m)
    a = int(a)
    e = int(e)
    i = int(i)
    o = int(o)
    O = int(O)
    E = int(E)

numbers.close()

x = 0
y = 0
z = 0

calcresults = []

numbers = open("Numbers.txt", "r")

for line in numbers:
    x = m*2
    y = m+a
    z = m+E
    calcresults.append(x)
    calcresults.append(y)
    calcresults.append(z)

print(calcresults)

calcresults = str(calcresults)

newnumbers = open("Newnumbers.txt", "w")
newnumbers.write(calcresults)

numbers.close()
newnumbers.close()`

Solution

  • This is what you intended:

    numbers = open("Numbers.txt", "r")
    
    calcresults = []
    
    for line in numbers:
        (m, a, e, i, o, O, E) = line.split(",")
        print(line)
        m = int(m)
        a = int(a)
        e = int(e)
        i = int(i)
        o = int(o)
        O = int(O)
        E = int(E)
        x = m*2
        y = m+a
        z = m+E
        calcresults.append(x)
        calcresults.append(y)
        calcresults.append(z)
    
    print(calcresults)
    
    calcresults = str(calcresults)