我正在尝试将字典写入.txt文件。我还没有找到一种有效的方法来为文本文档添加多个键值。
FullNote:
allOf:
- $ref: '#/components/schemas/BaseNote'
- type: object
title: A single note response
required:
- id
- dateCreated
- profile
properties:
id:
type: integer
format: int32
dateCreated:
type: integer
format: int64
profile:
type: object
$ref: '#/components/schemas/Profile'
example:
id: 123456789
dateCreated: 1509048083045
profile:
$ref: '#/components/schemas/Profile'
我有一个字典,其中包含多个键值。该计划的这一部分让我:
players = {}
def save_roster(players):
with open("Team Roster.txt", "wt") as out_file:
for k, v in players.items():
out_file.write(str(k) + ', ' + str(v) + '\n\n')
display_menu()
我的目标是:
Bryce, <__main__.Roster object at 0x00000167D6DB6550>
答案 0 :(得分:0)
Python本身并不了解如何打印对象。您需要定义__str__
方法,以告诉python如何将对象表示为字符串;否则它将默认为您获得的表示。在你的情况下,我可能会使用像
def __str__(self):
return str(self.position)+", "+str(self.jersey)
或您要打印的任何属性。
从文本文件中读回数据:
with open("Team Roster.txt", "r") as in_file:
for line in in_file:
player = Roster(*(line.split(", "))
#do something with player, like store it in a list
假设Roster.__init__()
已正确设置,即通过按顺序传入文件每行中的参数来初始化Roster对象。