假设我有一本字典,我想将它写入现有文件。我怎样才能这样做而不丢失文件中可能已经存在的任何内容?我在想的是做以下事情:
def write_report(r, filename):
input_filename=open(filename, "a")
input_filename.close()
for (k,v) in r.items():
input_filename.write(k,v)
return filename
我想确保文件名正确包含字典。
最佳答案
您可以使用 json
模块以 JSON 格式读取和写入数据结构(换句话说,序列化为 JSON 并从 JSON 反序列化)。
例如:
import json
# load from file:
with open('/path/to/my_file.json', 'r') as f:
try:
data = json.load(f)
# if the file is empty the ValueError will be thrown
except ValueError:
data = {}
# save to file:
with open('/path/to/my_file.json', 'w') as f:
data['new_key'] = [1, 2, 3]
json.dump(data, f)
关于python - 如何将字典写入现有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20169493/