I have a program that takes input from user like; Name, Age and Email.
I store this info in a list (list1) then convert this list to string (mylist) and write to a text file like this:
mylist = str(list1)
with open("StudentRecord.txt",'a') as f:
f.write(merge+"\n")
This works fine to write to file and read/display the whole file.
My Question is: How do I search for a particular string in the text file and return data from it. For example: User types a name and we look for that string in file and return his age.
Format of Text file is like this:
James, 29, jimmy@company.com
Anthony, 29, jimmy@company.com
Jason, 29, jimmy@company.com
User wants to find age of Jason.
As Giovani stated in his comment, for large sets of data pandas would be a better option. However you can search and retrieve a users age via lists & list comprehension as follows;
with open('file.txt') as file:
data = list(file)
name = input('Enter a Name: ')
age = [i.split(',')[1].strip() for i in data if name in i][0]
print(f"Name: {name}\nAge: {age}")
Enter a Name: James
Name: James
Age: 29
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.