timsterc
timsterc

Reputation: 1033

How to find last line in csv file when using DictReader

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(']')

Upvotes: 1

Views: 691

Answers (2)

blhsing
blhsing

Reputation: 106946

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)))

Upvotes: 1

Loaii abdalslam
Loaii abdalslam

Reputation: 1

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

Upvotes: 0

Related Questions