python 如何將字典值寫入乙個文字檔案?

2021-10-25 08:24:49 字數 1226 閱讀 3755

我有乙個字典,我打算把它寫入乙個檔案。

exdict =

with

open

('file.txt'

,'r')as

file

:file

.write(exdict)

我遇到了這樣的錯誤:

file

.write(exdict)

typeerror: must be str

,not

dict

我修復了剛才的錯誤

'''

'''exdict =

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 =

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讀取文字變為字典

python如何將資料寫入本地txt文字檔案

一 讀寫txt檔案 1 開啟txt檔案 file handle open 1.txt mode w 上述函式引數有 1.檔名,mode模式 mode模式有以下幾種 w 只能操作寫入 r 只能讀取 a 向檔案追加 w 可讀可寫 r 可讀可寫 a 可讀可追加 wb 寫入進製資料 w模式開啟檔案,如果而檔...

python如何將資料寫入本地txt文字檔案

一 讀寫txt檔案 1 開啟txt檔案 file handle open 1.txt mode w 上述函式引數有 1.檔名,mode模式 mode模式有以下幾種 w 只能操作寫入 r 只能讀取 a 向檔案追加 w 可讀可寫 r 可讀可寫 a 可讀可追加 wb 寫入進製資料 w模式開啟檔案,如果而檔...

Python 如何將字串轉為字典

在工作中遇到乙個小問題,需要將乙個python的字串轉為字典,比如字串 user info 我們想把它轉為下面的字典 user dict 有以下幾種方法 1 通過 json 來轉換 import json user info user dict json.loads user info user d...