Problem 4.3
Paste
Write a program paste.py
that takes two files as command-line arguments and contacenates the corresponding lines in those two files with a tab character and prints it.
For example, of the first file files/a.txt
has the following contents:
A
B
C
D
and the second file files/b.txt
has the following:
1
2
3
4
The output should be:
$ python paste.py files/a.txt files/b.txt
A 1
B 2
C 3
D 4
Note that the first line is "A\t1"
.
For simplicity, assume that both the files have exactly same number of lines.
Hint:
You can use the strip
method on a string to remove the new line character.
>>> "a\n".strip("\n")
"a"
Solution
import sys
f1 = sys.argv[1]
f2 = sys.argv[2]
for left, right in zip(open(f1), open(f2)):
left = left.strip("\n")
right = right.strip("\n")
print(f"{left}\t{right}")