1

我有以下功能,它为 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)

谢谢你的帮助!

4

1 回答 1

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
于 2013-03-28T15:51:56.240 回答