繁体   English   中英

在 Python 中存储和打印文本文件中的数据

[英]Storing and Printing data from text file in Python

我有一个程序可以从用户那里获取输入; 姓名、年龄和电子邮件。

我将此信息存储在列表(list1) 中,然后将此列表转换为字符串(mylist)并写入文本文件,如下所示:

mylist = str(list1)
with open("StudentRecord.txt",'a') as f:
                f.write(merge+"\n")

这适用于写入文件和读取/显示整个文件。

我的问题是:如何在文本文件中搜索特定字符串并从中返回数据。 例如:用户输入一个名字,我们在文件中查找该字符串并返回他的年龄。

文本文件的格式是这样的:

James, 29, jimmy@company.com
Anthony, 29, jimmy@company.com
Jason, 29, jimmy@company.com

用户想要找到 Jason 的年龄。

正如 Giovani 在他的评论中所说,对于大量数据,pandas 将是更好的选择。 但是,您可以通过列表和列表理解来搜索和检索用户年龄,如下所示;

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])}")

我已经使用正则表达式来查找与搜索字符串对应的年龄

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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