2016-09-27 767 views
-5

我是python的新手。我想要做的是将文件'a'和文件'b'通过LINE整合到一个文件LINE中。Python]将两个文本文件合并为一个(逐行)

例如,

text file a = a ("\n") b("\n") c

text file b = 1("\n")2("\n") 3 

文本文件中的新将包含a 1("\n") b 2("\n") c 3

def main(): 
    f1 = open("aaa.txt") 
    f2 = f1.readlines() 
    g1 = open("bbb.txt") 
    g2 = g1.readlines() 
    h1 = f2+g2 
    print(h1) 

我很抱歉,这是使用计算器我第一次..

+5

你试过? – Harsha

+0

谢谢你的回复。我已经尝试了很多不同的东西,也许你会笑了:(我想出了如何制作一个(“\ n”)b(“\ n”)c(“\ n”)1(“\ n” )2(“\ n”)3,但我找不到任何地方在谷歌(逐行):( – user6886108

+0

欢迎来到StackOverFlow user6886108 !!!请检查此链接 - http://stackoverflow.com/help/how问问 –

回答

0

点:

  • 使用with打开文件。无需关闭文件。
  • 使用zip函数来组合两个列表。

代码,而拉链与评论在线:x.txt的

combine =[] 

with open("x.txt") as xh: 
    with open('y.txt') as yh: 
    with open("z.txt","w") as zh: 
     #Read first file 
     xlines = xh.readlines() 
     #Read second file 
     ylines = yh.readlines() 
     #Combine content of both lists 
     #combine = list(zip(ylines,xlines)) 
     #Write to third file 
     for i in range(len(xlines)): 
     line = ylines[i].strip() + ' ' + xlines[i] 
     zh.write(line) 

内容:y.txt的

1 
2 
3 

内容:

a 
b 
c 

内容z.txt的:

a 1 
b 2 
c 3 

代码压缩功能:

with open("x.txt") as xh: 
    with open('y.txt') as yh: 
    with open("z.txt","w") as zh: 
     #Read first file 
     xlines = xh.readlines() 
     #Read second file 
     ylines = yh.readlines() 
     #Combine content of both lists and Write to third file 
     for line1, line2 in zip(ylines, xlines): 
     zh.write("{} {}\n".format(line1.rstrip(), line2.rstrip())) 
+0

谢谢。如果我想让z.txt为1(“\ n”)b 2(“\ n”)c 3(“\ n”)? – user6886108

+0

非a(“\ n”)1(“\ n”)b(“\ n”)2(“\ n”)c(“\ n”)3 – user6886108

+0

检查更新后的代码 –

0

详细了解文件处理和使用in-bui lt功能有效。 对于你的查询只是使用h1 = f2+g2不是这样。

a=open('a.txt','r').readlines() 
b=open('b.txt','r').readlines() 
with open('z.txt','w') as out: 
    for i in range(0,10): #this is for just denoting the lines to join. 
     print>>out,a[i].rstrip(),b[i] 
+0

哇..你做了我的一天。从昨天开始一直在处理这个问题,为了写出一个新的文件,你应该怎么做而不是打印(a [i] .rstrip(),b [i])?我知道我应该从newfile开始= open(“new”,“w”) – user6886108

+0

如果行数超过10,该怎么办? –

+0

@ user6886108 @Dinesh而不是10,您可以使用文件a或文件b的行数最少的行。当你使用哪条线比另一条线多时。这行('print a [i] .rstrip(),b [i]')会抛出错误。 –