简体   繁体   English

字典到txt文件

[英]Dictionary to a txt file

I am trying to write a dictionary to a .txt file. 我试图将字典写入.txt文件。 I haven't found an efficient way to add multiple values for keys to a text doc. 我还没有找到一种有效的方法来为文本文档添加键的多个值。

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()

I have a dictionary that has multiple values for the key. 我有一本字典,其中有多个键值。 This part of the program leave me with: 程序的这一部分让我拥有:

Bryce, <__main__.Roster object at 0x00000167D6DB6550>

Where the out put i am aiming for is: 我要针对的目标是:

Bryce, 23, third, 23

Python doesn't inherently understand how to print an object. Python本质上不了解如何打印对象。 You need to define the __str__ method in order to tell python how to represent your object as a string; 您需要定义__str__方法,以告诉python如何将您的对象表示为字符串。 otherwise it will default to the representation you're getting. 否则,它将默认为您得到的表示形式。 In your case, I might go with something like 就您而言,我可能会选择类似

def __str__(self):
   return str(self.position)+", "+str(self.jersey)

or whichever attributes you want to print. 或您要打印的任何属性。

And to read the data back in from the text file: 并从文本文件读回数据:

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

Assuming Roster.__init__() is set up appropriately, ie a Roster object is initialized by passing in the parameters in each line of the file in order. 假设正确设置了Roster.__init__() ,即通过按顺序在文件的每一行中传入参数来初始化Roster对象。

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

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