使用DictReader时如何在csv文件中查找最后一行 [英] How to find last line in csv file when using DictReader

查看:167
本文介绍了使用DictReader时如何在csv文件中查找最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将.csv文件转换为.json文件.因为我有多个csv记录,并且需要对多个json对象进行操作,所以我在考虑创建一个数组.结果文件看起来不错,但最后一条记录的末尾有逗号.我一直在试图弄清楚如何不包括该逗号,但未能做到这一点.

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

推荐答案

您可以先将DictReader生成器生成的dict记录转换为列表,然后再将其转储为JSON:

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

这篇关于使用DictReader时如何在csv文件中查找最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆