2013-03-28 17 views
1

我有以下功能,需要3个信息(姓名,年龄,家乡)3人并将其保存在txt文件中。Python - 为字符串搜索文本文件

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

你为什么存储单独的行一个人的信息?使用','或tab – karthikr

回答

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