简体   繁体   中英

How to create a dictionary based on a text file?

I'm writing a simple python game where I have a text file in the following format where the key on the left is the player's name and the value on the right is the player's score:

Name 134

Next Name 304958

Etc....

Question: How can I read in a text file in that format and create a dictionary from the values on each line, and once the player exits the program, the file is updated with the latest dictionary entries?

I already have some code commented out that I've started but have been unable to implement and get working. Any help is appreciated.

Here is my code:

    # with open('scores.txt', 'r') as file:
    #     scores = {}
    #     for line in file:
    #         line = line.split()
    #         do stuff


    # with open("scores.txt", "w") as f:  # Save dictionary in file
    #     do stuff

To load that format:

with open('scores.txt', 'r') as infile:
    scores = {}
    for line in infile:
        name, _, score = line.rpartition(' ')
        scores[name] = int(score)

To save that format:

with open('scores.txt', 'w') as outfile:
    for name, score in scores:
        outfile.write('%s %s\n' % (name, score))

penne12 is correct, though. You could save a few lines of code by using the json library to store JSON instead of this particular text format.

Here's an example that uses JSON as suggested in the comments:

import json
def load_game_data():
    data = None
    with open('savegame.json', 'r') as savefile:
        data = json.load(savefile)

    return data


def save_game_data(data):
    with open('savegame.json', 'w') as savefile:
        json.dump(data, savefile)

# Store the game data as a dictionary:
data = { 'player_name' : 'wolfram', 'hp' : 8 }
save_game_data(data)
data = load_game_data()

print(data)
# prints {'player_name': 'wolfram', 'hp': 8}
print(data['player_name'])
print(data['hp'])

The data gets saved to disk as JSON and is loaded from disk as a dictionary, which is easy to use. You'll need to add code error handling, of course, this is just intended as a simple illustration.

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.

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