Home > Blockchain >  How do i save .json files in specific folder in python
How do i save .json files in specific folder in python

Time:12-16

I am using python and I wrote script, that makes from .csv a .json file... it works great but i would like to save those json files into different folder.

Where do I write path ?

import csv
import json
import glob
import os


for filename in glob.glob("Csv/*.csv"):
csvfile = os.path.splitext(filename)[0]

jsonfile = csvfile   '.json'

with open(csvfile '.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open(jsonfile, 'w') as f:
    json.dump(rows, f,indent=4)

CodePudding user response:

You need to specify the full path of the json file.
Now you are just put the name of the file and the result of this is that the file is written in the same directory.

Try to do something like this;

with open("my/path/{}".format(jsonfile), 'w') as f:
    json.dump(rows, f,indent=4)

CodePudding user response:

You might use os.path.join for this as follows, for example

jsondir = "jsons"
with open(os.path.join(jsondir,jsonfile), 'w') as f:
    json.dump(rows, f,indent=4)

disclaimer: I assume jsons catalog does already exists

CodePudding user response:

Here are a few useful hacks:

Using os and __file__ you can consitently (OS independent) get a file's directory

FILE_DIR: str = os.path.dirname(os.path.abspath(__file__))

Getting to parent folders can be done with pathlib

from pathlib import Path

PARENT_DIR: str = Path(FILE_DIR).parent.as_posix()

Finally, you can get the user's home directory via os.path.expanduser("~").

Once you have the folder you want, the rest should be straightforward.

  • Related