2016-03-25 13 views
-1

私はPythonプログラミングではかなり新しいです。Pythonのテキストファイル(ID付き)の結合/結合

私はテーブルをマージすることができますが、今は私が特定のIDでテーブルをマージ/ジョインする必要があるときに困っています。

2つの.txtファイルがあります。 TXT1で

は、私のような番号(ID)を持っている:私は(または類似)のような結果に何かを取得したいと思い、私はIDが

1 733786 102807 
2 734475 102995 
3 735009 103403 
4 734878 103728 
5 735694 103722 

との座標を持っているTXT2で

5 
3 
4 
1 
2 

をどこ順序を保持してtxt1の数字の横に正しい座標を見ることができます

5 735694 103722 
3 735009 103403 
4 734878 103728 
1 733786 102807 
2 734475 102995 

私は試しましたこのコードに

with open("1.txt", "r") as a, open("2.txt", "r") as b: 
    h = {line1.strip():line2.strip() for line1,line2 in zip(a,b)} 
with open("RESULT.txt", "w") as out: 
    for k,v in h.iteritems(): 
     out.write("{} {}\n".format(k,v)) 

を使用しますが、それは良いですが、順番ではありません、

1 4 734878 103728 
3 2 734475 102995 
2 5 735694 103722 
5 1 733786 102807 
4 3 735009 103403 
+1

あなたが実際にあなたとあなたを助けるために私たちを見せたい何かを試してみましたか?またはあなたの仕事や宿題を誰かがあなたのためにやることを望んでいるだけですか? –

答えて

0
with open("text2") as f: 
    data = dict(row.split(None,1) for row in f) 
with open("output.txt","wb") as f_out,open("text1") as f: 
    for line in f: 
     f_out.write("%s %s" % (line.strip,data.get(line.strip(),"")) 
+0

ありがとうございます。 –

0

これはトリックを行う必要が重要であろう参加し、以下の結果を与えました。ようこそ。次回はこれまでに試したことをお見せしましょう。

with open('txt1.txt') as file1: 
    txt1 = file1.read().splitlines() 

with open('txt2.txt') as file2: 
    txt2 = file2.read().splitlines() 

with open('txt1.txt', 'w') as new_file: 
    new = '' 
    for line_a in txt1: 
     for line_b in txt2: 
      if line_a[0] == line_b[0]: 
       new_file.write(line_b + '\n') 
+0

ありがとうございました!私はやるだろうが、私のバージョンはデッドエンドだと恐れていた! –