4

I have JSON data stored in a file (Movies.json). i want to read the file and do some process and then save the output in new file

with open("Movies.json",'r') as f: movies = json.loads(f.read()) // doing some process 

How can i save the output?

Currently, I am trying this but it's not working:

json.dump(movies, f) 
0

4 Answers 4

3

for output you need to use 'w' instead of 'r'

import json # Opening JSON file f = open('movies.json') # returns JSON object as # a dictionary movies = json.load(f) # Iterating through the json # list for i in movies: print(i['id']) # output with open("Movies.json", 'w') as f: json.dump(movies, f) # Closing file f.close() 
Sign up to request clarification or add additional context in comments.

Comments

3

You are using 'r' it is for reading, you should use 'w'

import json with open("Movies.json", 'w') as f: json.dump(movies, f) 

Comments

1

You need to let the file be closed and then reopen it for write and write the modified object back again:

with open("Movies.json", 'w') as f: json.dump(movies, f) 

Comments

0
with open("Movies.json",'r') as rf: with open("New_Movies.json",'w') as wf: movies = json.loads(rf.read()) #doing some process movies_after_process = do_something(movies) wf.write(json.dumps(movies_after_process)) 

Comments