I am trying to write a dictionary to a .txt file. 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. You need to define the __str__
method in order to tell python how to represent your object as a string; 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.