繁体   English   中英

如何使用 python 从字典中写入文件

[英]How to write to a file from a dictionary with python

我有某种我想遵循的格式。 它是这样的。

1个

2个BB

3 立方厘米

ETC

由单个空格分隔的键和值。 我有将它变成字典的代码,但是我不知道如何做相反的事情。 我必须将文件内容写入字典的代码是。

    def readlines(self):
        self.user_list = {}
        for line in score_file:
            (key, val) = line.split()
            self.user_list[key] = val

我需要在程序执行过程中更新所述字典,然后以相同的格式将更新的内容打印到文件中。如果用于执行上述代码相反的代码遵循类似的格式而不需要导入任何模块。 该文件是 in.txt。 谢谢您的帮助。

您只能将字符串写入文件而不是字典。 为此,您必须将字典转换为字符串,然后将其推送到文件中。

import json

myDict = {1: 'value1',2:'value2'}

with open('myfile.txt', 'w') as file:
     file.write(json.dumps(myDict))

我建议您在每次需要时关闭文件。 所以它不会一直打开。

def write_to_file(self):
   # w for write mode
   score_file = open('rating.txt', 'w', encoding='utf-8')
   to_write = ""
   # please rename self.user_list as it is not a list but a dictionary
   for key in self.user_list.keys():
       # value + space + key + new line
       to_write += self.user_list[key] + " " + key + "\n" 
   score_file.write(to_write)
   # if you don't need the file anymore, close it
   score_file.close()

暂无
暂无

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

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