1

I am trying to store the jsonas text file , I am able to print the file but am not able to store the file and also the o/p is coming wiht unicode charatcer.

PFB code.

import json
from pprint import pprint
with open('20150827_abc_json') as data_file:
    f=open("file.txt","wb")
    f.write(data=json.load(data_file))
    print (data)>f
    f.close()

When i execute it , the file gets created but its of zero byte and also how can i get rid of unicode character and also store the output.

o/p

u'Louisiana', u'city': u'New Olreans'
2
  • 1
    You simply copy the content of one file to another ? Why not just copy it ? Commented Mar 17, 2016 at 13:31
  • 1
    What are you expecting to happen at print (data)>f because 1) data isn't defined and 2) you are printing a greater than comparison, not f.write(data) Commented Mar 17, 2016 at 13:36

2 Answers 2

2

To serialize JSON to file you should use json.dump function. Try to use following code

import json
from pprint import pprint
with open('20150827_abc_json') as data_file, open('file.txt','w') as f:
    data=json.load(data_file)
    print data
    json.dump(data,f)
Sign up to request clarification or add additional context in comments.

1 Comment

You could add f to the with statement by adding a comma
0

the print syntax is wrong, you put only a single > while there should be two of them >>. in python 3 (or python2 if you from __future__ import print_function) you can also write, in a more explicit way:

print("blah blah", file=yourfile)

I would also suggest to use a context manager for both files:

with open('20150827_abc_json') as data_file:
    with open("file.txt","wb") as file:
        ...

otherwise you risk that an error will leave you destination file pending.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.