如何将字典写入现有文件?

use*_*300 14 python dictionary python-3.3

假设我有一本字典,我想将其写入现有文件.如何在不丢失文件中可能存在的任何内容的情况下这样做?我在想的是做了以下事情:

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
Run Code Online (Sandbox Code Playgroud)

我想确定的是文件名正确包含字典.

Eug*_*nov 25

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

  • 当然,只是想让OP知道这个问题;) (2认同)

fly*_*yer 7

泡菜可能是另一种选择:

import pickle

output = open('output.txt', 'ab+')
data = {'a': [1, 2, 3],}

pickle.dump(data, output)
output.close()

# read data
output = open('output.txt', 'rb')
obj_dict = pickle.load(output)    # 'obj_dict' is a dict object
Run Code Online (Sandbox Code Playgroud)

但是只有pickle序列化的数据才能使用pickle.load读取.因此,如果您想要读取文件中的所有数据,您应该所有数据pickle.dump放入文件中.