2016-09-27 7 views
-5

私はPythonを初めて使う人です。私がやろうとしているのは、ファイル 'a'とファイル 'b'をLINEで1つのファイルLINEにまとめることです。例えばPython] 2つのテキストファイルを1つに結合する(行単位で)

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

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

テキストは、私は、これはstackoverflowのを使用して、私の最初の時間ですごめんなさい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、私はgoogleのどこにも行を見つけることができませんでした:( – user6886108

+0

StackOverFlowへようこそuser6886108 !!!このリンクをチェックしてください - http://stackoverflow.com/help/how -to-ask –

答えて

0

ポイント:withを使用して

  • ファイルを開きます。ファイルを閉じる必要はありません。
  • zipを使用して2つのリストを結合します。コメントをインラインでジッパーなし

コード: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

( "\ 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

あなたは私の一日を作りました。あなたが作ったものに新しいファイルを書くには、print(a [i] .rstrip()、b [i])の代わりに何をすればよいでしょうか?私はnewfile – user6886108

+0

行が10より大きい場合はどうすればいいですか? –

+0

@ user6886108 @Dinesh 10の代わりに、ファイルaのlenまたは行数が最小のファイルbを使用できます。あなたが使用しているときは、他のものより多くの行を持っています。この行( 'print a [i] .rstrip()、b [i]')はエラーを投げます。 –

関連する問題