简体   繁体   English

使用 Python 通过随时间向其写入键/值对来在 txt 文件中构建字典

[英]Use Python to build a dictionary in a txt file by writing key/value pairs to it over time

How can I "build" a dictionary within a txt file using Python, over time?随着时间的推移,如何使用 Python 在 txt 文件中“构建”字典?

I need to take two variables, for example...我需要取两个变量,例如...

some_string = "Hello, World!"

some_float = 3958.8

...then write those two variables to a txt file, as a dictionary. ...然后将这两个变量作为字典写入 txt 文件。

For the key/value pair, some_string should be the key, and some_float should be the value.对于键/值对, some_string 应该是键,而 some_float 应该是值。

Next time I run the program, some_string and some_float may be different, and will need to get written/added to the same txt file, essentially adding another key/value pair to the now already existing dictionary (txt file).下次我运行该程序时, some_string 和 some_float 可能会有所不同,并且需要写入/添加到同一个 txt 文件中,本质上是将另一个键/值对添加到现在已经存在的字典(txt 文件)中。 If the new key (some_string) is not different, then compare the new value (some_float) with the old value already in the txt file, and if the new value is lesser, then update it in the txt file.如果新键(some_string)不一样,则将新值(some_float)与txt文件中已有的旧值进行比较,如果新值较小,则在txt文件中更新。

All I've been able to find is information regarding adding a known dictionary to a txt file, not building one up over time.我所能找到的只是有关将已知字典添加到 txt 文件的信息,而不是随着时间的推移建立一个。 In my case, I don't know ahead of time what some_string and some_float will be next time I run the program, so I can't pre-build the dictionary and just write it all to the txt file at once.就我而言,我不知道下次运行程序时 some_string 和 some_float 会是什么,所以我无法预先构建字典并一次将其全部写入 txt 文件。

Any ideas?有任何想法吗?

You can use open file mode append ('a') to append to the file the new content and update the file that way every time you add a new value.您可以使用打开文件模式附加 ('a') 将新内容附加到文件中,并在每次添加新值时以这种方式更新文件。 Here's an exemple on how to do it:这是一个如何做到这一点的例子:

def add_dic(key, value):
    with open('dic.txt', mode='a') as fp:
        fp.write(key + " " + str(value) + '\n')


def read_dic():
    dic = {}
    with open('dic.txt', mode='r') as fp:
        for line in fp.readlines():
            words = line.split(' ')
            key = words[0]
            value = float(words[1])
            dic[key] = value

    return dic


some_string = input("string: ")
some_float = float(input("float: "))

add_dic(some_string, some_float)

dic = read_dic()
print(dic)

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

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