Last active
June 14, 2023 05:13
-
-
Save keithweaver/ae3c96086d1c439a49896094b5a59ed0 to your computer and use it in GitHub Desktop.
Save JSON file with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
def writeToJSONFile(path, fileName, data): | |
filePathNameWExt = './' + path + '/' + fileName + '.json' | |
with open(filePathNameWExt, 'w') as fp: | |
json.dump(data, fp) | |
# Example | |
data = {} | |
data['key'] = 'value' | |
writeToJSONFile('./','file-name',data) | |
# './' represents the current directory so the directory save-file.py is in | |
# 'test' is my file name |
nice :) thank u
Nice Job Thank a lot
Thnk's
Great job
what if i wanted to add more data as to what it previously had?
what if i wanted to add more data as to what it previously had?
use the a
file permission instead of w
, so it would be
with open("file.txt", "w") as f:
f.write("Hello ")
with open("file.txt", "a") as f:
f.write("World!")
file.txt
Hello World!
Well, in the case you are dealing with json, you cant do that, so you would have to first read the file
and then rewrite it from scratch using the already read data
in that case it would be
# Save the file
import json
with open("out.json", "w") as f:
json.dump(f, [1, 2, 3])
# r+ is for both reading and writing
with open("out.json", "r+") as f:
existing_data = json.load(f) # load [1, 2, 3] from the file
existing_data.extend([4, 5, 6]) # add [4, 5, 6] to the loaded data
json.dump(f, existing_data) # write [1, 2, 3, 4, 5, 6] to the file
out.json
[1, 2, 3, 4, 5, 6]
How to create a JSON file and save it to a specific folder?
I have created a JSON file but it gets saved in my project folder but I want to save it in another folder.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not use:
import os
os.path.join('.', path, filename + '.json')
This solution is more error proof than yours.