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

标签 python file 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中的数据?

最佳答案

你可以这样做:

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

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

关于python - 如何在 python 文件处理中从 namedtuple 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44353009/

相关文章:

c# - 确定文件在哪个物理硬盘上?

php - 检测文件中的空行

python - Python 中的 "named tuples"是什么?

python - 通过键入创建 NamedTuple 时引发 TypeError

python - 为什么通过字段名访问 namedtuple 比访问类的成员变量慢?

python - Peewee ORM查询结果fn.COUNT是unicode类型,而不是整数

python - App Engine 后端配置 (python)

python - 为什么 Python 3 中的复数求幂如此之快?

c++ - VC++ 2012 无法读取大于 4 GB 的文件

python - 避免在 python 上使用 utf-8