[英]How to read a line in a .txt file and create a list?
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 =客戶編號,名字,姓氏,DOB,hnumber,郵政編碼,性別
現在,我想通過輸入客戶編號來搜索文件,然后繪制特定信息,例如僅打印郵政編碼等。我該怎么做?
我是python的新手,不勝感激
假設您的“文件文本”如下所示:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.