utdlegend utdlegend - 6 months ago 11
Python Question

Writing lists of data to a text file column by column

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

Answer

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')
Comments