2017-08-11 30 views
-1

我有一個打印3位信息,姓氏,姓氏和出生日期的程序。這些都存儲在單獨的文本文件中。一個文本文件的每一行都帶有其他文本文件的相同行號。 我要打印的信息是這樣的:如何從多個文件打印相應的行?

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

你可以試試這個:

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