我有两个文件:
档案A:
line A_1
line A_2
line A_3
...
line A_n
档案B:
line B_1
line B_2
...
line B_n
line B_n+1
...
line B_m
我希望文件A的第一行n
替换文件B的第一行n
行(m > n
)。在此文件B之后应如下所示:
档案B:
line A_1
...
line A_n
line B_n+1
...
line B_m
对此最狡猾的解决方案是什么?
答案 0 :(得分:2)
with open("newB.txt","wb") as fout:
with open("B.txt") as b:
for lineA,lineB in zip(open("A.txt"),b):
fout.write(lineA)
fout.writelines(b)
也许......我猜......
答案 1 :(得分:0)
with open(A) as fp_A:
for i, line in enumerate(fp_A):
if i <= n:
print(line)
else:
break
with open(B) as fp_B:
for i, line in enumerate(fp_B):
if i > n:
print(line)