user1640255
user1640255

Reputation: 1304

Python write two lists to a 2 column txt file, reopen and adding data, rewrite

I have two list of almost 100 float numbers values each and I need to save their data into one txt file with two columns. But, I need this file to reopen it and adding extra Data and save it, at least 3 times in my code... please if someone have any idea ...

Upvotes: 0

Views: 7286

Answers (2)

Ashok Kumar Jayaraman
Ashok Kumar Jayaraman

Reputation: 3085

You can try this idea:

First, write two lists into a two column text file.

a=[0.2342,2.0002,0.1901]
b=[0.4245,0.5123,6.1002] 
c = [a, b] 
with open("list1.txt", "w") as file:
    for x in zip(*c):
        file.write("{0}\t{1}\n".format(*x))

Second, reopen the saved file list1.txt

with open("list1.txt", "r+") as file:
    d = file.readlines()

Third, Adding extra data

e=[1.2300,0.0002,2.0011]
f=[0.4000,1.1004,0.9802]
g = [e, f]
h = []
for i in d:
    h.append(i)
for x in zip(*g):
    h.append("{0}\t{1}\n".format(*x))

Fourth, save the text file

with open("list2.txt", "w") as file1:
    for x in h:
        file1.writelines(x)

Output in the list2.txt file looks as follows

0.2342  0.4245
2.0002  0.5123
0.1901  6.1002
1.23    0.4
0.0002  1.1004
2.0011  0.9802

Upvotes: 1

nneonneo
nneonneo

Reputation: 179392

It depends on how you want to separate the two columns (with spaces, tabs or commas). Here's how I'd do it the quick 'n' dirty way with a space as the separator:

Python 2:

with open('output.txt', 'w') as f:
    for f1, f2 in zip(A, B):
        print >> f, f1, f2

Python 3:

with open('output.txt', 'w') as f:
    for f1, f2 in zip(A, B):
        print(f1, f2, file=f)

Upvotes: 0

Related Questions