Write file in JSON

2

I have a series of files in JSON format, so work better organize all of them into a single file using the following method:

import json 

filename = "dados_geral.json"

for mensagens in range(1,6):
    arq='data_gephi_%d.json' % (mensagens)

    with open(arq,'r') as f:
       for linha in f:
           tweet = json.dumps(linha)
           filename.write(tweet)
filename.close()

However, when trying to separate the data that one joined and rewrites them as they were before using

import json 


with open('dados_juntos.json','r') as f: 
    c=0
    for linha in f: 
        c+=1
        file = 'dados_%d.json'%(c)
        arq = open(file,'wb')
        tweet = json.loads(linha)# ->Transforma uma string JSON em objeto.
        #tweet = json.dumps(linha)#-> Transforma um objeto em string JSON.
        #print(type(tweet))
        arq.write(tweet)
    arq.close()

When I use .dumps it writes the file as str and loses access to the file hierarchy and when trying and using .loads the error occurs

TypeError: a bytes-like object is required, not 'dict'

So how can I write a file linking all my data and then separating without losing access to information?

    
asked by anonymous 12.12.2017 / 14:26

1 answer

1

The source files have broken lines so maybe you should use the code below (as I did not have the files I did not test so there may be some errors) ...

import json 

filename = "dados_geral.json"

for mensagens in range(1,6):
    arq='data_gephi_%d.json' % (mensagens)

    with open(arq,'r') as f:
       conteudo = f.readlines()
       tweet = json.dumps(comteudo)
       filename.write(tweet)
       filename.write("# /* SEPARADOR */")
filename.close()

To read the file something like this:

import json

with open('dados_juntos.json','r') as f: 
    c=0
    msg=''
    for linha in f: 
        if not linha.startswith('# /* SEPARADOR */'):
            msg += linha
        else:
            c+=1
            file = 'dados_%d.json'%(c)
            arq = open(file,'wb')
            arq.write(msg)
            arq.close()
    
12.12.2017 / 15:08