Reputation: 133
In python 3,3
import json
peinaw = {"hi":4,"pordi":6}
json_data = open('data.json')
json.dump(peinaw, json_data)
json_data.close()
i get
File "C:\Python33\lib\json\__init__.py", line 179, in dump
fp.write(chunk)
io.UnsupportedOperation: not writable
tried same thing in 2,7 and it works.I s there a different way in 3,3?
Upvotes: 3
Views: 4548
Reputation: 19486
You are not opening the file for writing. The file is opened in a read
mode. to verify do this:
json_data = open('data.json')
print (json_data) # should work with 2.x and 3.x
To solve the probem, just open the file in write
mode.
json_data = open('data.json', 'w')
Also, you should use the with
statement when woking with files.
with open('data.json', 'w') as json_data:
json.dump(peinaw, json_data)
Upvotes: 2
Reputation: 133754
>>> import json
>>> peinaw = {"hi":4,"pordi":6}
>>> with open('data.json', 'w') as json_data: # 'w' to open for writing
json.dump(peinaw, json_data)
I used a with
statement here, where the file is automatically .close()
d at the end of the with
block.
Upvotes: 5
Reputation: 22571
You need to open file for writing, use 'w' mode parameter:
json_data = open('data.json', 'w')
Upvotes: 1