0

I have a JSON file which is 5 lines long. I want to write each line to a seperate file, i.e write line1 to file1, line2 to file2 etc

Now, I am trying to write the file in a file, but data is in a line and disorder, and there is a weird 'u' before each key and value on the writing file.

import json

with open("test1.json") as f:
    with open("1.json","w") as o:
        lines = f.readline()
        for line in lines:
            y =  json.loads(line)
            print(y)
            json.dump(y,o)
Legorooj
  • 2,646
  • 2
  • 15
  • 35
Jesse
  • 161
  • 11

2 Answers2

1
   linecount = 0 
   with open("test1.json") as f:
        lines = f.readline()
        for line in lines:
            linecount = linecount + 1
            with open(str(linecount)+".json","w") as o:
                y =  json.loads(line)
                print(y)
                o.writelines(y)

Updated: added @tripleee suggestion

fp = open("test1.json",'r')
for i, line in enumerate(fp):
    with open(str(i)+".json","w") as o:
        y =  json.loads(line)
        print(y)
        o.writelines(y)

Everything looks good in your code except this line with open("1.json","w") as o: change this line to create new file for each line

logic is - Count the line, Create file with linecount.json and dump the json

backtrack
  • 7,996
  • 5
  • 52
  • 99
1

The most effective way to do this would be:

with open('test1.json').readlines() as json_data:  # readlines returns a list containing each line as seperate items
    for i in range(len(json_data)):  # For loop allows this to work with any number of lines
        file = open(f'{str(i+1)}.json', 'w')  # Same as '{str(i+1)}.json'.format() or str(i+1)+'.json'
        file.write(json_data[i])
        file.close()
        # print(json.loads(json_data[i]) # Uncomment if you want to print the content of each line

This allows you to work with any number of lines - dynamically naming the output file for you.

The u in front of the strings (like u'string') means unicode string. This is now a deprecated inclusion of the python language - the defualt string type is unicode. It is now only in python 3 for compatibility with python 2.

(source: What's the u prefix in a Python string?)

Legorooj
  • 2,646
  • 2
  • 15
  • 35