[譯]如何將字典值寫入一個文本文件?


原文來源:https://stackoverflow.com/questions/36965507/writing-a-dictionary-to-a-text-file

我有一個字典,我打算把它寫入一個文件。

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
    file.write(exDict)

我遇到了這樣的錯誤:

file.write(exDict)
TypeError: must be str, not dict

我修復了剛才的錯誤

exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
    file.write(str(exDict))

但另一個錯誤出現了

file.write(str(exDict))
io.UnsupportedOperation: not writable

第一個錯誤是因為:你要用read模式打開一個文件,嘗試寫入內容。這個需要查看python IO模塊
第二個錯誤是因為:你只是將字符串寫入文件。如果你想要寫入字典對象,你要么需要將它轉為string對象,要么將它轉化為可序列化對象。
下面是Python3的寫法:

import json
# as requested in comment
exDict = {'exDict': exDict}
with open('file.txt', 'w') as file:
     file.write(json.dumps(exDict)) 
# 使用json.loads讀取文本變為字典
In case of serialization
import cPickle as pickle
with open('file.txt', 'w') as file:
     file.write(pickle.dumps(exDict)) 
# 使用pickle.loads讀取文本變為字典


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM