[英]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.