使用函数从文本文件中检索特定数据。 Python 3

时间:2014-12-04 17:23:19

标签: list function python-3.x text tuples

有一个外部文本文件,其中包含列中的信息。

例如:

文本文件如下所示:

123 1 645 Kallum Chris Gardner
143 2 763 Josh   Brown Sinclar

现在数字“1”和“2”是年。我需要编写一个程序来获取当年的输入并打印出有关个人的其他信息。

所以我将在程序中输入“2”并打印出'143 2 763 Josh Brown Sinclar'

到目前为止,我得到了这样的代码。我如何继续前进?

def order_name(regno, year, course, first_name, middle_name, last_name=None):
    if not last_name:

            last_name = middle_name
    else:

            first_name =  first_name, middle_name
    return  (last_name, first_name,regno, course, year)

1 个答案:

答案 0 :(得分:1)

你可以这样做:

f = open('your_file.txt')
lines = f.readlines()
res = [x for x in lines if str(year) in x.split()[1]]
print res