thamy
thamy

Reputation: 183

json dump() into specific folder

This seems like it should be simple enough, but haven't been able to find a working example of how to approach this. Simply put I am generating a JSON file based on a list that a script generates. What I would like to do, is use some variables to run the dump() function, and produce a json file into specific folders. By default it of course dumps into the same place the .py file is located, but can't seem to find a way to run the .py file separately, and then produce the JSON file in a new folder of my choice:

import json
name = 'Best'
season = '2019-2020'
blah = ['steve','martin']

with open(season + '.json', 'w') as json_file:
    json.dump(blah, json_file)

Take for example the above. What I'd want to do is the following:

Right now my issue is that I can't find a way to produce the file in a specific folder. Any suggestions, as this does seem simple enough, but nothing I've found had a method to do this. Thanks!

Upvotes: 10

Views: 21407

Answers (4)

Wups
Wups

Reputation: 2569

Python's pathlib is quite convenient to use for this task:

import json
from pathlib import Path

data = ['steve','martin']
season = '2019-2020'

Paths of the new directory and json file:

base = Path('Best')
jsonpath = base / (season + ".json")

Create the directory if it does not exist and write json file:

base.mkdir(exist_ok=True)
jsonpath.write_text(json.dumps(data))

This will create the directory relative to the directory you started the script in. If you wanted a absolute path, you could use Path('/somewhere/Best').
If you wanted to start the script while beeing in some other directory and still create the new directory into the script's directory, use: Path(__file__).resolve().parent / 'Best'.

Upvotes: 7

soumya-kole
soumya-kole

Reputation: 1365

First of all, instead of doing everything in same place have a separate function to create folder (if already not present) and dump json data as below:

def write_json(target_path, target_file, data):
    if not os.path.exists(target_path):
        try:
            os.makedirs(target_path)
        except Exception as e:
            print(e)
            raise
    with open(os.path.join(target_path, target_file), 'w') as f:
        json.dump(data, f)

Then call your function like :

write_json('/usr/home/target', 'my_json.json', my_json_data)

Upvotes: 7

Use os.path.join():

with open(os.path.join(name, season+'.json'), 'w') as json_file

The advantage above writing a literal slash is that it will automatically pick the type of slash for the operating system you are on (slash on linux, backslash on windows)

Upvotes: 1

Sivaram Rasathurai
Sivaram Rasathurai

Reputation: 6333

Use string format

import json
import os
name = 'Best'
season = '2019-2020'
blah = ['steve','martin']
try: 
    os.mkdir(name) 
except OSError as error: 
    print(error)  
 
with open("{}/{}.json".format(name,season), 'w') as json_file:
    json.dump(blah, json_file)

Upvotes: 2

Related Questions