简体   繁体   中英

Storing and Printing data from text file in Python

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

 import re name = input("Enter the name\\n") with open("f.txt",'r') as f: line=f.readlines() for i in line: if re.match(name,i): age=re.findall(r'\\d+',i) print(f"Age of the {name} is {int(age[0])}")

I have used regular expression to find the age corresponds to the search string

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM