My question looks exactly like this post : Append float data at the end of each line in a text file
But for me, it is different. I have a dat file containing over 500 lines. I want that for each line, it adds me the value of the corresponding line in the second file. This second file only contains values like 0 or 1 in one column.
What I have :
File 1 : File 2 :
1 2 3 4 0
1 2 3 4 1
1 2 3 4 0
What I want :
File 1 : File 2 :
1 2 3 4 0 0
1 2 3 4 1 1
1 2 3 4 0 0
What I've already tried :
Y = np.loadtxt('breastcancerY')
def get_number(_):
lines = []
for line in Y:
print('this is a line', line)
return " " + str(line) + '\n'
with open("breastcancerX","r") as f:
data = f.read()
out = re.sub('\n',get_number,data)
with open("output.txt","w") as f:
f.write(out)
When I do that and I print my values in file of 0 and 1, all the values are 0, it doesn't correspond to my file.
EDIT 1 :
Using this code :
# first read the two files into list of lines
with open("breastcancerY","r") as f:
dataY = f.readlines()
with open("breastcancerX","r") as f:
dataX = f.readlines()
# then combine lines from two files to one line.
with open("output.dat","w") as f:
for X,Y in zip(dataX,dataY):
f.write(f"{X} {Y}")
It gives me this