I am very beginner Python. So my question could be quite naive. I just started to study this language principally due to mathematical tools such as Numpy and Matplotlib which seem to be very useful.
In fact I don't see how python works in fields other than maths I wonder if it is possible (and if yes, how?) to use Python for problems such as text files treatment.
And more precisely is it possible to solve such problem:
I have two files A.txt and B.txt . The A.txt file contains three columns of numbers and looks like this
0.22222000 0.11111000 0.00000000
0.22222000 0.44444000 0.00000000
0.22222000 0.77778000 0.00000000
0.55556000 0.11111000 0.00000000
0.55556000 0.44444000 0.00000000
.....
The B.txt file contains three columns of letters F or T and looks like this :
F F F
F F F
F F F
F F F
T T F
......
The number of lines is the same in files A.txt and B.txt
I need to create a file which would look like this
0.22222000 0.11111000 0.00000000 F F F
0.22222000 0.44444000 0.00000000 F F F
0.22222000 0.77778000 0.00000000 F F F
0.55556000 0.11111000 0.00000000 F F F
0.55556000 0.44444000 0.00000000 T T F
.......
In other words I need to create a file containing 3 columns of A.txt and then the 3 columns of B.txt file.
Could someone help me to write the lines in python needed for this?
I could easily do it in fortran but have heard that the script in python would be much smaller. And since I started to study math tools in Python I wish also to extend my knowledge to other opportunities that this language offers.
Thanks in advance
Of course Python can be used for text processing (possibly it is even better suited for that than for numerical jobs). The task in question, however, can be done with a single Unix command: paste A.txt B.txt > output.txt
And here is a Python solution without using numpy:
with open('A.txt') as a:
with open('B.txt') as b:
with open('output.txt', 'w') as c:
for line_a, line_b in zip(a, b):
c.write(line_a.rstrip() + ' ' + line_b)
If you want to concatenate them the good ol' fashioned way, and put them in a new file, you can do this:
a = open('A.txt')
b = open('B.txt')
c = open('C.txt', 'w')
for a_line, b_line in zip(a, b):
c.write(a_line.rstrip() + ' ' + b_line)
a.close()
b.close()
c.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With