2013-12-03 216 views
0
def search(): 
    num = input("Type Number : ") 
    search = open("Customerlist.txt", 'r') 
    for line in search: 
    if str(num) in line: 
     print (line) 
     filetext = str(line) 

我正在寫一個股票系統。我已經編寫了代碼來創建客戶,並將他們的詳細信息寫入文件filetext = customernumber,firstname,surname,DOB,hnumber,postcode,Gender
我現在想通過輸入客戶編號來搜索文件,然後畫出特定的信息,如打印郵政編碼等等。我該怎麼做?如何讀取.txt文件中的一行並創建列表?

我是新來的Python和任何幫助表示讚賞

+1

看看這個 - > http://docs.python.org/2/tutorial/inputoutput.html –

+0

請包括你想要的文本文件的例子寫。這將有助於清除問題,例如每行是一人還是每行都是一個字段等。 –

+2

另外,我不認爲您真的想要推出自己的數據存儲。爲什麼不使用['json'模塊](http://docs.python.org/2/library/json.html)? –

回答

1

假設你的「FILETEXT」看起來是這樣的:

1, Alice, Alison, 010180, 55, 2500, F 

然後你可以檢索你從這樣的文件要什麼:

def find(): 
    num = 1 
    f = open('Customerlist.txt', 'r') #Open file 
    search = f.readlines() #read data into memory (list of strings) 
    f.close() #close file again 
    for line in search: 
     lst = line.split(", ") #split on the seperator - in this case a comma and space 
     if str(num) == lst[0]: #Check if the string representation of your number equals the first parameter in your lst. 
      print "ID: %s" % lst[0] 
      print "Name: %s" % lst[1] 
      print "Surname: %s" % lst[2] 
      print "DOB: %s" % lst[3] 
      print "hnumber: %s" % lst[4] 
      print "Postcode: %s" % lst[5] 
      print "Gender: %s" % lst[6] 

將輸出:

ID: 1 
Name: Alice 
Surname: Alison 
DOB: 010180 
hnumber: 55 
Postcode: 2500 
Gender: F 

這應該幾乎涵蓋了您的需求。但是請注意,我完全沒有辦法刪除特殊字符,行結尾等。您應該能夠輕鬆搞定。提示 - 你要找的方法是strip()

相關問題