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
我现在想通过输入客户编号搜索文件,然后绘制特定信息,如打印邮政编码等。我该怎么做?
我是python的新手,感谢任何帮助
答案 0 :(得分: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()