1

I have the following code that transforms a .csv file to a .json one. Because I have multiple csv records, and I will need to operate on multiple json objects, I was thinking of creating an array. The resulting file looks good, EXCEPT that the last record has a trailing comma. I have been trying to figure out how to not include that comma, but have not been able to do so.

csvfile = open('file.csv','r')
jsonfile = open('file.json','w')

reader = csv.DictReader(csvfile)
jsonfile.write('[')

for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write(',')
    jsonfile.write('\n')
jsonfile.write(']')
timsterc
  • 963
  • 3
  • 10
  • 18

2 Answers2

1

You can convert the dict records produced by the DictReader generator into a list first before dumping it as JSON:

jsonfile.write(json.dumps(list(reader)))
blhsing
  • 91,368
  • 6
  • 71
  • 106
0
a=open('file.txt','rb')
lines = a.readlines()
if lines:
    first_line = lines[:1]
    last_line = lines[-1]

check this :
StackOverFlow question 1
StackOverFlow question 2