简体   繁体   中英

How to save multiple outputs from a for loop in python to a text file?

I'm trying to save the output of the for loop in a text file along with its corresponding variables. However, when I do the following I only get the last line as an output.

a = [1,2,3,4]
    
b = [4,5,6,7]

c = [5]

file=open("my_output.txt", 'a')

for i, j in zip(a, b):
    z = (i**2)*j+c[0]
    print (z)
    z = str(z)
    
file.write(z + "\n")
file.close()

My output:

117

What I'm looking for:

a,b,c,z
1,4,5,9
2,5,5,25
3,6,5,59
4,7,5,117

Would appreciate any support. Thank you in advance.

Code to calculate the z. then write the a,b,c,z into the file.

    a = [1, 2, 3, 4]
    b = [4, 5, 6, 7]
    c = [5]
    zs = []
    col = ['a','b','c','z']
    file = open("my_output.txt", 'a')
    for i, j in zip(a, b):
        z = (i ** 2) * j + c[0]
        print(z)
        zs.append([i,j,c[0],z])
    file.write(str(zs))
    file.close()

The issue in your code is that you are writing outside your loop and thus getting the last value only. Writing inside the loop will fix it.

There is a simpler way. print can write to files:

# python 3.6+

a = [1,2,3,4]
b = [4,5,6,7]
c = [5]

with open("my_output.txt", 'a+') as f:
    print('a,b,c,z', end='\n', sep=',', file=f)
    for i, j in zip(a, b):
        print(f'{i},{j},{c[0]},{(i**2)*j+c[0]}', end='\n', sep=',', file=f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM