2
I have a number of files in JSON format, to work better organize them all in 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 gathered and rewrite 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 the . dumps it writes the file as str and I lose access to the file hierarchy and while trying and using the . loads error occurs
TypeError: a bytes-like object is required, not 'dict'
So how can I write a file uniting all my data and then separating without losing access to information?
This doesn’t seem to make sense. Why do you need to save all the files in one and then separate them? How will you know when you start and end the contents of a particular file within the
dados_juntos.json
? Because the logic you put in the question would save each line in a different file and this seems to be far from what you want to do.– Woss
It is that I have a series of tweets saved separately in JSON files. So instead of having 10k of tweets files I would like to have only 1 with all of them, in this format, one per line. But as you can see when writing all in a single file it ceases to be a file of the type dic and becomes str and this is not interesting for me, since I still want to have access to the hierarchy of the data. That is why the question of how to write the file keeping the access possible arose.
– Rennan Céos Gleyson
The problem is similar to this, take a read on the solution. Note that if you just want to transcribe the contents of one file to another, you don’t need to use the module
json
; just read and write the content.– Woss
What I want to achieve is: I have two JSON files, I want to write a general file containing these two in it so that later I can separate and evaluate them separately. But by writing this general file the data in it ceases to be a dictionary and becomes strings. I believe transcribing would not help, but I will look yes, thank you.
– Rennan Céos Gleyson