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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20169493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:44:56  来源:igfitidea点击:

How to write a dictionary into an existing file?

pythondictionarypython-3.3

提问by user300

Let's say I have a dictionary and I want to write it into an existing file. How can I do so without losing anything that could potentially already exist in the file? What I was thinking of is doing the following:

假设我有一本字典,我想将它写入现有文件中。如何在不丢失文件中可能已经存在的任何内容的情况下执行此操作?我在想的是做以下事情:

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

what I want to make sure is that the filename correctly contains the dictionary.

我想确保文件名正确包含字典。

回答by Eugene Naydenov

You can use jsonmodule to read and write data structures in JSON format (in other words serialize to JSON and deserialize from JSON). For example:

您可以使用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)

回答by flyer

picklemay be another choice:

泡菜可能是另一种选择:

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

But only the data that has been serialized by picklecould be read using pickle.load. So if you want to read all data from the file, you should pickle.dumpall the data into the file.

但是只能使用pickle.load读取已被pickle序列化的数据。所以如果你想从文件中读取所有数据,你应该pickle.dump所有数据到文件中。

回答by Yann Vernier

What you've already done using open(filename, "a")uses append mode - which is nearly all you need. In append mode, you'll never overwrite what's already in the file. The problem is that it doesn't guarantee you're the only one writing - and if any writes might be partial, they may come out garbled if there are ever multiple writers working on the same file. That sort of issue can be avoided using file locking.

您已经open(filename, "a")使用附加模式完成的操作 - 这几乎是您所需要的。在追加模式下,您永远不会覆盖文件中已有的内容。问题是它并不能保证你是唯一一个写入的人——如果任何写入可能是部分的,如果有多个写入者在同一个文件上工作,它们可能会出现乱码。使用文件锁定可以避免这类问题。

The code you posted has a couple more problems, however, such as closing the file before writing to it, and the fact that write only accepts one string argument. You'll want to serialize data into manageable chunks, for which Python's own standard module is pickle(and shelvestores things in database files), and JSON is a more widely supported format.

但是,您发布的代码还有一些问题,例如在写入文件之前关闭文件,以及 write 仅接受一个字符串参数的事实。你会想序列数据转换成可管理的块,为此,Python的标准模块是咸菜(和搁置在数据库文件存储的东西),和JSON是更广泛支持的格式。

回答by mediocrity

If you want to append a text representation of each key-value pair in the dictionary into a text file you could look into the following approach:

如果要将字典中每个键值对的文本表示附加到文本文件中,您可以查看以下方法:

def write_report(r, filename):
    input_file=open(filename, "a")
    for k, v in r.items():
        line = '{}, {}'.format(k, v) 
        print(line, file=input_file)        
    input_file.close()

The above can be expressed more cleanly with the with statment.

以上可以用 with 语句更清晰地表达。

def write_report(r, filename):    
    with open(filename, "a") as input_file:
        for k, v in r.items():
            line = '{}, {}'.format(k, v) 
            print(line, file=input_file)