用另一个文件的内容替换文件头

时间:2016-07-04 22:19:32

标签: python

我有两个文件:

档案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

对此最狡猾的解决方案是什么?

2 个答案:

答案 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)