简体   繁体   English

如何从多个文件中打印相应的行?

[英]How to print corresponding lines from multiple files?

I have a program which prints 3 bits of information, forename, surname and date of birth. 我有一个程序可以打印3位信息,包括姓氏,姓氏和出生日期。 These are all stored in separate text files. 这些都存储在单独的文本文件中。 Each line of one text file goes with the same line number of the other text files. 一个文本文件的每一行与其他文本文件的行号相同。 I want to print the information like this: 我想打印这样的信息:

John Smith 02/01/1980

My code does this but is very long, is there a way to shorten my code and still print the information the way i want. 我的代码可以执行此操作,但是很长,有没有一种方法可以缩短我的代码并仍然按我希望的方式打印信息。 The code below prints the information of 10 people. 下面的代码打印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()

File objects are iterators , so you could use zip() to aggregate the corresponding lines from all the files, eg 文件对象是迭代器 ,因此您可以使用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))

You can try this: 您可以尝试以下方法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM