[Tutor] creating .json files

Alan Gauld alan.gauld at yahoo.co.uk
Thu Apr 13 13:51:48 EDT 2017


On 13/04/17 17:32, Rafael Knuth wrote:
> Is there a way to split these two into separate steps:
> a) creating a .json file
> b) manipulating it (a, r, w ...)

Of course.

> What if I just wanted to create a .json file and do nothing with it?
> 
> import json
> file_name = "my_numbers.json"
> 
> The above does not do the job. What am I getting wrong here? Thanks.

The above creates a variable called file_name that stores a string.
It has nothing to do with any files.

You need to open the file to create it:

with open(file_name,'w') as json_file: pass

Will open a new file and immediately close it again.

You could do the same explicitly with

json_file = open(file_name,'w')
json_file.close()

Remember that variable names are just labels for your benefit.
The fact that you call it file_name means nothing to Python,
you might as well call it xcdseqplrtyg123 so far as Python is concerned,
its just a lablel. The name is only meaningful to
you (and possibly to other human readers).

Similarly, although your string looks like a file name to
a human reader, to Python it's just a string of characters.
Python cannot draw any meaning from that.

Finally, the code above creates a new file called my_numbers.json
But it is an empty file and is NOT a json file, despite the name.
It only becomes a json file once you add some json data to it.
open() creates text files, it has no understanding of what the
data you write to those files means.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list