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)
I am writing a stock system. I have written code to create a customer and write their details to a file eg filetext = customernumber, firstname, surname, DOB, hnumber, postcode, Gender
I now want to search the file by inputting the customer number and then draw out specific info like just printing postcode etc. How do I do this?
I am new to python and any help is appreciated
Assuming your "filetext" looks like this:
1, Alice, Alison, 010180, 55, 2500, F
Then you can retrieve what you want from the file like this:
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]
Will output:
ID: 1
Name: Alice
Surname: Alison
DOB: 010180
hnumber: 55
Postcode: 2500
Gender: F
This should pretty much cover your need. However do note that I have done absolutely NOTHING to remove special characters, line endings etc. You should be able to figure that out easily. Hint - the method you look for is strip()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.