How to add whitespace when appending values extracted from txt file in python

In a text file I have two columns of value (x and y)
The file was read and it was split using space and appended in x and y.
but while appending x values, it is continuous without any space.
How to add space or to make it appear in new line for every appended value.

import numpy as np 

x = []
y = []

for line in open('IV.txt', 'r'):
    lines = [i for i in line.split(" ")]
    x.append(lines[0])
    y.append(lines[1])

f1 = open('xdata.txt','a')
f1.writelines(x)
f1.close()

f2 = open('ydata.txt','a')
f2.writelines(y)
f2.close()

the input data is

0 3
0.2 3.4
0.4 3.6
0.6 3.8
0.8 4.2
1 5.3
1.2 5.5
1.4 5.8
1.6 6.0
1.8 6.4
2 6.8
2.2 7.1
2.4 7.8
2.6 8.2
2.8 8.4
3 8.8

So the output of x appears as
00.20.40.60.811.21.41.61.822.22.42.62.83

>Solution :

f.writelines(" ".join(x))
f.writelines("\n".join(x))

You can put space or newline like this.

ADD

you can get x, y array from input data like this.

x = list()
y = list()
with open("data.txt", "r") as f:
    for line in f.readlines():
        split_line = line.split()
        x.append(split_line[0])
        x.append(split_line[1])

Leave a Reply