0

I have an issue where I need to use simplejson to write some dictionaries to file using python 2.4 (yes, we're actively trying to upgrade; no, it's not ready yet).

Python 2.4 cannot use the syntax:

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

and I cannot find the correct syntax anywhere. If I try using this:

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

nothing happens. The file is created, but nothing is in it.

So, does anybody know how to do this for python 2.4?

3
  • 1
    dump saves, load reads. which one are you trying to do? Commented Jun 17, 2015 at 21:25
  • 1
    In the first example, you are using json.dumps (a write activity) and in the second you are using json.loads (a read activity on a file you have opened for writing). Did you mean to do this? Commented Jun 17, 2015 at 21:26
  • 1
    oops! Sorry about that--a copy/paste mistake on my part. Commented Jun 17, 2015 at 21:35

3 Answers 3

1

To save JSON to file use json.dump:

sov_filename = 'myfile.txt' sov_file = open(sov_filename, 'w') json.dump(data, sov_file) 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm trying to write to the file--my original post had a copy/paste problem. This will try to read a file that doesn't exist.
And this does not work. Regardless of using dump or dumps, the file will be created, but nothing is in it.
What kind of data do you put to dump?
@roninveracity, you are closing the file right? (e.g. sov_file.close())
0

The with syntax is syntactic sugar. The desugared equivalent is:

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

I'm not sure why simplejson isn't writing to the file, but you can work around that as well, by replacing json.dump(data, outfile) with outfile.write(json.dumps(data))

Comments

0

I simply needed to close() it. I had it in the code, but was exiting before it executed. I was accustomed to this not being necessary because I was using the csv writer in a python 2.7 script, for which the lines appear in the file without explicitly closing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.