Deleting File Lines in Python

后端 未结 3 597
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 15:17

I am trying to create a program that takes in a username and high score, if they are already a user they update to their new high score or just adds the high score if not.

3条回答
  •  旧巷少年郎
    2021-01-28 16:00

    I'd advise you to move to some standard format of saving information, such as JSON, YAML, XML, CSV, pickle or another. Then what you need is to read and parse the file into native data structure (probably dict in the case), modify it (it is trivial), and write it back.

    Example with json (human readable, quite easy to use):

    import json
    
    # loading data
    try:
        with open("data") as a:
            b = json.load(a) # b is dict
    except FileNotFoundError:
        b = {}
    
    # user 
    name = input("What's your name? ")
    score = int(input("What's your high score? "))
    
    # manipulating data
    b[name] = score
    
    # writing back 
    with open("data", "w") as a:
        json.dump(b, a)
    

    Example with shelve (not human-readable, but extremely easy to use):

    import shelve
    
    name = input("What's your name? ")
    score = int(input("What's your high score? "))
    
    with shelve.open("bin-data") as b:
        b[name] = score # b is dict-like
    

提交回复
热议问题