Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

python - how to read from text in a style of dictionary?

I want to make a program that reads info from text (dictionary). If key does not exist, program should add this key and keyvalue also must be added to the text file line by line. I did something but in reading part, there is problem saying list index out of range. Can anyone help ?

with open('text.txt','r') as file:
    x={}
    for line in file:
        key = line.rstrip().split(':')[0]
        keyvalue = line.rstrip().split(':')[1]
        x[key]=keyvalue
while True:
    name = input('whose hobby you wanna learn?:')
    if name in x:
        print('Name found')
        print("%s's hobby is %s" %(name,x[name]))
    else:
        print('i do not know',name)
        answer = input('do you wanna add this person?(yes or no)')
        if answer == ('yes'):
            new_user= input('type the name of new person:')
            new_user_hobby = input('type the hobby of that person:')
            x[new_user] = new_user_hobby
            with open('text.txt','a') as file:
                file.write('
')
                file.write(new_user)
                file.write(':')
                file.write(new_user_hobby)
            print('person created successfully!')
question from:https://stackoverflow.com/questions/65890054/how-to-read-from-text-in-a-style-of-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use JSON.

File data.json

{
    "key1": "value1",
    "key2": "value2"
}

File main.py

import json

with open("data.json", "r") as jsonfile:
    data = json.load(jsonfile)
    key = input("enter key: ")
    if key in data:
        print("key %s has value %s" % (key, data[key]))
    else:        
        add = input("key %s was not found in the data; do you want to add it ? " % key)
        if add:
            value = input("enter value for key %s : " % key)
            data[key] = value
    jsonfile.close()
    with open("data.json", "w") as jsonfile:
        json.dump(jsonfile, data)

If you run it, enter key3, then enter yes, then value3, and the data.json file will be like this:

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...