La Brewers
La Brewers

Reputation: 39

How to create json file in a directory?

I got an error.

FileNotFoundError: [Errno 2] No such file or directory:'Users/bea/Desktop/iSight/Webservertesting/json/data1.json'

This is the code that I was running. Could you please help me fix this error.

import json

def writeToJSONFile(path, fileName, data):
    filePathNameWExt =  path + '/' + fileName + '.json'
    with open(filePathNameWExt, 'r') as fp:
        json.dump(data, fp)
        fp.write(data)

writeToJSONFile("Users/bea/Desktop/iSight/Webservertesting/json", "data1", "book")

Upvotes: 0

Views: 2423

Answers (1)

Kwsswart
Kwsswart

Reputation: 541

Te problem here is you need to change the 'r' to 'a' or 'w'

def writeToJSONFile(path, fileName, data):
    filePathNameWExt =  path + '/' + fileName + '.json'
    with open(filePathNameWExt, 'a') as fp:
        json.dump(data, fp)
        fp.write(data)

writeToJSONFile("Users/bea/Desktop/iSight/Webservertesting/json", "data1", "book")

The reason for this is:

  • 'r' opens a file thats there with read only.
  • 'a' opens a file to append, however if it is not there it creates the file.
  • 'w' opens a new file and writes too it, but if a file is there it overwrites the file

Upvotes: 2

Related Questions