create a json file in Python 3.6.1

0

I want to create a json file and save it in a path x, below the code I'm occupying.

import json
import os
ruta = {}
ruta['nombre']= 'Jose'
ruta['edad']='15'
ruta['nacionalidad']='Mex'
carpeta = 'C:%sPruebas' % os.sep
os.chdir(carpeta) #esta es la linea que hace que se cambie el lugar de trabajo
with open('data.json', 'w') as outfile:
    carpeta = 'C:%sPruebas' % os.sep
    archivo = json.dump(ruta,outfile)
    
asked by Memo 08.02.2018 в 01:01
source

2 answers

2

You are saving the file in the current working directory, if you want to save it in " C: \ Tests " you must pass the path to open . To create your route, I recommend using os.path.join instead of concatenating / formatting strings:

import json
import os

data = {}
data['nombre'] = 'Jose'
data['edad'] = '15'
data['nacionalidad'] = 'Mex'

dir = 'C:/Pruebas'  # También es válido 'C:\Pruebas' o r'C:\Pruebas'
file_name = "data.json"

with open(os.path.join(dir, file_name), 'w') as file:
    json.dump(data, file)
    
answered by 08.02.2018 в 01:25
1

Since you indicate that you use python 3.6, I am going to make some recommendations to make more pythonic the code:

  • Instead of using the operator format '%' , it is recommended to use the f-strings or "format literals" .
  • Instead of contributing to file paths, it is recommended to use the pathlib module and try that your code works for any platform, even if you're working on windows.

As it seems, you want your json file to be saved in C:\Pruebas , a path that only exists in windows. Therefore you should use pathlib.WindowsPath in this way:

from pathlib import WindowsPath

dir = WindowsPath('C:\Pruebas')
fichero = dir / "data.json"

with fichero.open("w") as fp:
    json.dump(data, fp)

As I would not have much text, the writing can be more direct:

fichero.write_text(json.dumps(data), encoding="utf8")
    
answered by 11.07.2018 в 11:04