python中将两个文件合并
有a.txt和b.txt,现在要求在c.txt中每输入一行a.txt后面输入10行b.txt.求大神指导。...
有a.txt和b.txt,现在要求在c.txt中每输入一行a.txt后面输入10行b.txt.
求大神指导。 展开
求大神指导。 展开
3个回答
推荐于2016-06-19 · 知道合伙人互联网行家
关注
展开全部
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()
展开全部
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()
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()
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你好:
其实这个问题不是很难啊:
请看代码:
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()
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询