2017-08-11 8 views
-1

私は3ビットの情報、姓、姓、生年月日をプリントするプログラムを持っています。これらはすべて別々のテキストファイルに保存されています。 1つのテキストファイルの各行は、他のテキストファイルの同じ行番号を使用します。 私はこのような情報を印刷したい:複数のファイルから対応する行を印刷する方法は?

John Smith 02/01/1980 

私のコードは、これを行いますが、非常に長いです、私のコードを短縮し、まだ情報私が望むように印刷する方法があります。以下のコードは、10人の情報を出力します。

def reportone(): 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[1-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[2-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[3-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[4-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[5-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[6-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[7-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[8-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[9-1], end='') 
    print() 
    for file in ["Forename", "Surname", "Date of birth"]: 
     with open(file) as f: 
      print(f.readlines()[10-1], end='') 
reportone() 

答えて

2

Fileオブジェクトイテレータあるので、あなたは、例えば、すべてのファイルから対応する行を集約するzip()を使用することができます

with open("file1.txt") as f1, open("file2.txt") as f2, open("file3.txt") as f3: 
    for lines in zip(f1, f2, f3): 
     print(*map(str.strip, lines)) 
+0

感謝を。 – user8435959

+0

空白を取り除くには、['str.strip()'](https://docs.python.org/3.6/library/stdtypes.html#str.strip)を使います。 –

+0

私はstr.strip()をどの行に入れるでしょうか – user8435959

0

あなたはこれを試すことができます。これは、しかし、それは3つのデータ、誕生と姓の日から2をインデント作品

titles = ["Forename", "Surname", "Date of birth"] 

data = [open("{}.txt".format(i)).readlines() for i in titles] 

for forename, surname, dob in zip(*data): 
    print(forename, surname, dob) 
+0

これは、行を読み終えた後にファイルを開いたままにしますか?それとも暗黙のうちに閉鎖されていますか? – Keatinge

+0

@Keatinge Pythonは、読み込み用に開かれたファイルを自動的に閉じます。 – Ajax1234

関連する問題