python中将两个文件合并

2024-11-26 21:49:18
推荐回答(3个)
回答1:

Python编程将两个文件合并,代码如下:

//例子:合并a.txt和b.txt文件
def readf(filename):
    lines = file(filename).readlines()
    dic = {}
    for i in lines:
        i_ = i.split()
        dic[i_[0]] = int(i_[1])
    return dic

dica = readf('a.txt')
dicb = readf('b.txt')

lines = []
for i in dica:
    percent = str(float(dicb[i])*100/dica[i])+'%'
    s = ' '.join([i, str(dica[i]), str(dicb[i]), percent])
    s += '\n'
    lines.append(s)
//合并成c.txt 
with open('c.txt', 'w') as f:
    f.writelines(lines)
    f.close()

回答2:

import os
a = []
b = []

for lineA in open('a.txt','r'):
a.append(lineA)
for lineB in open('b.txt','r'):
b.append(lineB)

c = open('c.txt','w+')
for line in a:
c.write(line)
for i in range(0,10):
if len(b)>0:
c.write(b[0])
del(b[0])
c.close()
a.close()
b.close()

回答3:

你好:

其实这个问题不是很难啊:

请看代码:

txtpath1=r"a.txt"
txtpath2=r"b.txt"
txtpath3=r"c.txt"

fpa=open(txtpath1)
fpb=open(txtpath2)
fpc=open(txtpath3,"w")

arrB=[]
for lineb in fpb.readlines():
    arrB.append(lineb)

index=0
for linea in fpa.readlines():
    index=index+1
    fpc.write(linea)
    for i in range((index-1)*10,(index)*10):
        try:
           fpc.write(arrB[i])
        except:
            pass
print "Done!"
fpa.close()
fpb.close()
fpc.close()