Python - 搜索字符串的文本文件

时间:2013-03-28 14:28:54

标签: python string text

我有以下功能,可以为3个人提供3条信息(姓名,年龄,家乡)并将其保存在txt文件中。

def peopleInfo():
    txtFile = open("info.txt", "w")
    i = 0
    for i in range(0, 3):
        name = input("Enter name ")
        age = input("Enter age ")
        hometown = input("Enter hometown ")
        txtFile.write(name + "\n" + age + "\n" + hometown + "\n")
    txtFile.close()

我现在正在尝试创建一个函数来读取文本文件并打印一个人名,如果他们的家乡是'牛津'。到目前为止,我有以下内容只是为了从文件中读取文本,但我不知道如果该镇是牛津,如何跳过一行并打印名称。

def splitLine():
    txtFile = open("info.txt", "r")
    for line in txtFile:
        line = line.rstrip("\n")
        print(line)

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我对以下任何感兴趣的人使用以下内容:

def peopleInfo():
    txtFile = open("info.txt", "w")
    i = 0
    for i in range(0, 3):
        name = input("Enter name ")
        age = input("Enter age ")
        hometown = input("Enter hometown ")
        txtFile.write(name + "\n" + age + "\n" + hometown + "\n")
    txtFile.close()

def splitLine():
    txtFile = open("info.txt", "r")
    lineList = []
    i = 0
    for line in txtFile:
        lineList.append(line.rstrip("\n"))
        if "Oxford" in lineList[i]:
            print(lineList[i - 2])
        i += 1