2013-03-28 30 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