簡體   English   中英

如何在python 2.4中編寫simplejson

[英]How to write simplejson in python 2.4

我有一個問題,我需要使用simplejson使用python 2.4編寫一些字典文件(是的,我們正在積極嘗試升級;不,它尚未准備好)。

Python 2.4不能使用以下語法:

with open('data.txt', 'w') as outfile:
    json.dumps(data, outfile)

而且我在任何地方都找不到正確的語法。 如果我嘗試使用此:

sov_filename = 'myfile.txt'
sov_file     = open( sov_filename, 'w' )
filecontents = json.dumps( sov_file )

什么都沒發生。 文件已創建,但是其中沒有任何內容。

那么,有人知道如何針對python 2.4做到這一點嗎?

要將JSON保存到文件,請使用json.dump

sov_filename = 'myfile.txt'
sov_file = open(sov_filename, 'w')
json.dump(data, sov_file)

with語法是語法糖。 減價后的等效項是:

outfile = open('data.txt', 'w')
try:
    json.dump(data, outfile)
finally:
    outfile.close()

我不確定為什么simplejson無法寫入文件,但是您也可以通過將json.dump(data, outfile)替換為outfile.write(json.dumps(data))

我只需要close()它。 我在代碼中有它,但是在執行之前就退出了。 我習慣於不必這樣做,因為我在python 2.7腳本中使用了csv編寫器,為此,這些行出現在文件中而沒有顯式關閉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM