Python 使用DictReader时如何查找csv文件中的最后一行
我有以下代码将.csv文件转换为.json文件。因为我有多个csv记录,并且需要对多个json对象进行操作,所以我考虑创建一个数组。结果文件看起来不错,只是最后一条记录后面有一个逗号。我一直在试图找出如何不包括逗号,但一直未能做到这一点Python 使用DictReader时如何查找csv文件中的最后一行,python,json,csv,Python,Json,Csv,我有以下代码将.csv文件转换为.json文件。因为我有多个csv记录,并且需要对多个json对象进行操作,所以我考虑创建一个数组。结果文件看起来不错,只是最后一条记录后面有一个逗号。我一直在试图找出如何不包括逗号,但一直未能做到这一点 csvfile = open('file.csv','r') jsonfile = open('file.json','w') reader = csv.DictReader(csvfile) jsonfile.write('[') for row in r
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转储:
jsonfile.write(json.dumps(list(reader)))
你能补充解释一下为什么这是答案吗?
jsonfile.write(json.dumps(list(reader)))