Exporting data in json or txt, in python?

0

I need help learning how to export data from an object. At first I need to export in type "txt" and / or "json", but I could not succeed in either.

The code:

#coding = utf-8
import json

.
.
.
 def arquivo(lista_nomes):
     print(json.dumps(lista_nomes))


 def txt(lista_nomes):
     arq = open('listaNomes.txt', 'w')
     arq.write(for i in lista_nomes:)
     arq.close()

for lista_nome in lista:
    txt(lista_nomes)
    arquivo(lista_nomes)
.
.
.
Trying to export with the "txt" function, I only get one line with just one name, and using json_dumps does not generate any output (I did not quite understand how to use the 'json' lib from python, I thought it was for exporting data .)

I also ask how do I output to be in UTF-8 charset? The output, when I print the result in the python compiler, comes with unrecognized characters, so I do not understand why the code is 'set' in utf-8.

I'm waiting for people to help me solve the problem.

    
asked by anonymous 10.09.2017 / 02:35

1 answer

0

Come on, one thing at a time.

The json module has two similar but different functions: dump , which accepts the object to be converted and a file , and dumps , which accepts only the object and returns a string .

To write a json file, therefore, it is more interesting to use dump :

import json

def escrever_json(lista):
    with open('meu_arquivo.json', 'w') as f:
        json.dump(lista, f)

def carregar_json(arquivo):
    with open('meu_arquivo.json', 'r') as f:
        return json.load(f)

minha_lista = ['João', 'Maria', 'José']
escrever_json(minha_lista)

print(carregar_json('meu_arquivo.json'))  # ['João', 'Maria', 'José']

For text, we use write to write. If we do not include the newline character, all names will be written without space, so we have to do this:

def escrever_txt(lista):
    with open('meu_arquivo.txt', 'w', encoding='utf-8') as f:
        for nome in lista:
            f.write(nome + '\n')

def carregar_txt():
    with open('meu_arquivo.txt', 'r', encoding='utf-8') as f:
        return f.readlines()

minha_lista = ['João', 'Maria', 'José']
escrever_txt(minha_lista)

print(carregar_txt())  # ['João\n', 'Maria\n', 'José\n']

If we want the names to come back without the newline character, we can slightly modify the function:

def carregar_txt():
    with open('meu_arquivo.txt', 'r', encoding='utf-8') as f:
        return [nome.strip() for nome in f.readlines()]
    
10.09.2017 / 17:54