Lily Sharpton Lily Sharpton - 7 months ago 10
Python Question

Replacing one column in a file with other values

I have a file like this:

1 0
1 0
1 0
2 0
2 0
2 0
3 0
3 0
3 0
3 0
3 0
4 0
5 0


and another file,
file2
with one column:

0.122
0.133
0.855
-2.1
-9.00


I want to replace the second column of file one with data from
file2
such that the output file becomes this:

1 0.122
1 0.122
1 0.122
2 0.133
2 0.133
2 0.133
3 0.855
3 0.855
3 0.855
3 0.855
3 0.855
4 -2.1
5 -9


In other words, I want to copy the data from second file to first until the first column value remains same. when the value in first column changes, it picks a second value from the other file.

I have been trying it in python and have been able to replace the column but not meet the repetitions the desired number of times. my code just copies the data into first 5 positions of column2 in first file and leaves the rest. Can someone suggest a solution please?

Answer

It would be better to see your code but this might help you get your logic tweaked (it doesn't write to the original file and it assumes that the second file has enough lines):

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'r')

oldF1Value = None
v = None

for l1 in f1:
    [c1, c2] = l1.split()
    if (oldF1Value != c1):
        oldF1Value = c1
        v = f2.readline().splitlines()[0]

    print(c1, v)

f1.close()
f2.close()