【问题标题】:Writing a dictionary to a csv file for another reuse将字典写入 csv 文件以供再次使用
【发布时间】:2016-08-04 13:12:36
【问题描述】:

我有一本字典:

inputdict = {key1: [value1,value2..], key2: [value1,value2..], key3: [value1,value2..]}

我想将数据写入 dict.csv 文件,格式如下:

key1: [value11,value12,..]
key2: [value1,value22,..]
key3: [value31,value32,..]

我写道:

import csv
with open(ouputfile, 'wb') as csv_file:
        writer = csv.writer(csv_file)
        for key, value in inputdict.items():
           writer.writerow([key: value])

但现在我有一个错误:

 TypeError: a bytes-like object is required, not 'str'

当我设法写出这样的文件时,我也想将它读回新字典。

字典包含键和整数列表中的字符串。我想通过读取 csv 文件来重用其他脚本的字典。

【问题讨论】:

    标签: python-3.x csv dictionary


    【解决方案1】:

    使用w 而不是wb 写入文件。并且在回读时使用r 而不是rb

    那么你可以这样做:

    with open('/path/to/input_dict.csv','w') as fou:
        writer = csv.writer(fou)
        for k,v in inputdict.iteritems():
            writer.writerow(["{'%s':%s}" % (k,v)])
    

    然后再读一遍:

    import ast
    with open('/path/to/input_dict.csv','r') as fin:
        for line in fin:
            ast.literal_eval(ast.literal_eval(line))
    

    但是,您应该能够使用pickle 更轻松地做您想做的事情:

    import pickle
    with open('/path/to/input.csv', 'wb') as fou:
        pickle.dump(inputdict,fou)
    

    阅读:

    with open('/path/to/input.csv', 'rb') as fin:
        inputdict = pickle.load(fin)
    

    【讨论】:

    • 感谢您的回复,我尝试了第一个选项,因为我必须将结果提供在像 csv 这样的可读文件中,以供其他程序使用。泡菜也可以吗?
    • 不客气。不,泡菜是不可能的。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2013-06-08
    • 2014-06-30
    • 2017-03-28
    • 2012-12-17
    • 1970-01-01
    相关资源
    最近更新 更多