Best Method In Writing A List To A Text File In Python?
Solution 1:
Since you are importing pandas, why don't you use it, too.
data = pd.read_table(myfile, header=None, sep='\s+')
data.columns = 't','x','y','z','Rx','Ry','Rz'
for column in data:
with open(column + ".txt", "w") as ofile:
ofile.write(' '.join(str(i) for i in data[column]))
Solution 2:
So if i understand the filestructure you want correctly:
you want each line to have 7 numbers in order "t z y x Rz Ry Rx" with space between them.
First you need to go through first element of all lists, than through second, etc...
To do so best may be zip (documentation)
with open(filename, 'w') as f: # We open file for writing
for line in zip(t, z, y, x, Rz, Ry, Rx):
line = [str(i) for i in line] # convert to strings
f.write(' '.join(line) + "\n") # joins space and ends the line
EDIT:
Ok, so if I now understand the format, the following shoud help:
with open('x.txt', 'w') as f:
f.write('\n'.join([str(i) for i in x]) + '\n') # omit "+ '\n'" if you don't want newline at the end of the file.
Repeate for each variable.
EDIT 2:
My explanation for why your methods don't work:
method 1
It's just how csv writer's writerows work
method 2
you are doing for each item in x, where x is list, not file you can write to. Corrected code:
with open('x.txt', 'w') as f:
for item in x:
f.write(str(item) + '\n')
note that '%s\n' can't work as item is int and s is for string, f.write('%d\n' % item) shoud work
method 3
str(x) formats list to the form you see it in file and you just write that into the file. The formating can be seen by doing print(str(x))
method 4
again same as in method 2
method 5
Similar to method 2. You don't define number anywhere. For it to work use:
with open('x.txt', 'w') as f:
for number in x:
f.write('%d\n' % number)
Post a Comment for "Best Method In Writing A List To A Text File In Python?"