Skip to main content
 首页 » 编程设计

python之如何在 python 文件处理中从 namedtuple 中提取数据

2025年02月15日8xiaohuochai

在 python 文件处理中从 namedtuple 中提取数据时遇到问题。 它在 --- 位置显示属性对象

from collections import namedtuple 
 
filename=input("Enter name of file ") 
Data=namedtuple('Data',['name','id','balance']) 
 
def write(): 
    file=open(filename,'a') 
    name=input("Enter name ") 
    idee=input("Enter ID ") 
    bal=input("Enter balance ")    
    data=Data(name,idee,bal) 
    file.write(str(data)) 
    file.close() 
 
def read(): 
    file=open(filename,'r') 
    for line in file: 
        print(Data.name,"\t",Data.id,"\t",Data.balance,"\n") 
 
write() 
write() 
read() 

如何提取data.name中的数据?

请您参考如下方法:

你可以这样做:

print("%s\t%d\t%s\n" % line) 

打印命名元组的内容。官方文档可能不是很明显,但是here is a good tutorial to understand named tuples