0

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.

3
  • You're only writing to the file outside the loop. What do you expect that does? Commented Sep 3, 2020 at 3:44
  • if you want to use single value why defining it as a list c = [5]? you can use c= 5 Commented Sep 3, 2020 at 3:46
  • Did you know print can write to files? Using f-string you can just print to file. See my example below. Commented Sep 3, 2020 at 4:23

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Oh that is way simpler! To be honest I wasn't aware that I can save with print function! Many thanks @ Prayson W. Daniel
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.