Reputation: 43
I have 3 lists, a,b,c how can I write them to a text file in the format of table (rows and columns) as this:
time(s) voltage(V) current(A)
0 0000000000 101101010
0.0005 0000110001 101011000
0.001 0001100000 101011000
I have tried to write:
powdata=open("powdata.txt","w")
for i in a:
powdata.write("%s\n"%i)
for j in b:
powdata.write("%s\n"%j)
powdata.close()
Unfortunately this kind of codes just writes data in the text file vertically I mean not like the suggested table
Upvotes: 0
Views: 5318
Reputation: 51
Assuming they are all the same length, use an index variable to pull the right entry from each. Here's the gist:
for i in len(a):
print(a[i], b[i], c[i])
Upvotes: -1
Reputation: 337
Use zip
to interleave the lists
a=['apple', 'banana', 'orange']
b=['a', 'b', 'c']
powdata=open("powdata.txt","w")
for val in zip(a,b):
powdata.write('{}, {}\n'.format(val[0], val[1]))
powdata.close()
Upvotes: 2
Reputation: 341
You could just use pandas? e.g.
import pandas as pd
df = pd.DataFrame({'time(s)' : [0, 0.005, 0.001], 'voltage(V)' : ['0000000000','0000110001','0001100000'], 'current(A)' : ['101101010','101011000','101011000']})
or, if
a = [0, 0.005, 0.001]
b = ['0000000000','0000110001','0001100000']
c = ['101101010','101011000','101011000']
you could just do
df = pd.DataFrame({'time(s)' : a, 'voltage(V)' : b, 'current(A)' : c})
then
df.to_csv('powdata.txt', sep='\t')
Upvotes: 0