如何从python中的文件处理中的namedtuple中提取数据
问题描述:
在python中的文件处理中无法从namedtuple中提取数据。 它显示在属性对象---位置如何从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
提取数据?
答
将数据写入文件时,它只是一个字符串,读取它时只能得到字符串。
from collections import namedtuple
import pickle
filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])
def write():
name=input("Enter name ")
idee=input("Enter ID ")
bal=input("Enter balance ")
data=Data(name,idee,bal)
with open(filename,'ab') as f:
pickle.dump(data,f)
def read():
with open(filename,'rb') as f:
while True:
try:
data=pickle.load(f)
print(data.name,"\t",data.id,"\t",data.balance,"\n")
except:
break
write()
write()
read()
答
你可以这样做:
print("%s\t%d\t%s\n" % line)
打印namedtuple的内容。官方文档可能不是很明显,但是here is a good tutorial to understand named tuples