[英]Convert CSV to JSON file in python
我想逐行解析 CSV 文件并将其转换为 JSON 并通过 websocket 发送。
我在网上找到了一些将 CSV 转换为 JSON 的代码,如下所示:
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
但是上面代码的问题是我们需要提到字段名称来解析CSV。 由于我有 2000 多行,这不是一个可行的解决方案。
谁能建议如何逐行解析 CSV 文件并将其转换为 JSON 而不指定字段名?
要在 Python 中将 CSV 转换为 JSON,请按照下列步骤操作:
csv.DictReader()
函数读取 CSV 文件的行。json.dumps()
将 Python 列表转换为 JSON 字符串。column_1,column_2,column_3
value_1_1,value_1_2,value_1_3
value_2_1,value_2_2,value_2_3
value_3_1,value_3_2,value_3_3
import csv
import json
import time
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
#convert python jsonArray to JSON String and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
start = time.perf_counter()
csv_to_json(csvFilePath, jsonFilePath)
finish = time.perf_counter()
print(f"Conversion 100.000 rows completed successfully in {finish - start:0.4f} seconds")
Conversion 100.000 rows completed successfully in 0.5169 seconds
[
{
"column_1": "value_1_1",
"column_2": "value_1_2",
"column_3": "value_1_3"
},
{
"column_1": "value_2_1",
"column_2": "value_2_2",
"column_3": "value_2_3"
},
{
"column_1": "value_3_1",
"column_2": "value_3_2",
"column_3": "value_3_3"
}
]
如果您对现有的解决方案感到满意,唯一困扰您的是如何输入列标题的“长”列表,我建议您使用 reader.next( ),
import csv
with open('your_CSV.csv') as csvFile:
reader = csv.reader(csvFile)
field_names_list = reader.next()
然后使用str.split(',')
将获得的字符串拆分为列表。
然后可以将您获得的列表提供给
fieldnames = (---from the above code block ---)
你的代码行。
假设您的 CSV 有一个标题行:只需从 DictReader 中删除 fieldnames 参数
如果省略 fieldnames 参数,则文件 f 第一行中的值将用作 fieldnames。 在https://docs.python.org/2/library/csv.html
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
reader = csv.DictReader(csvfile)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
你可以试试这个:
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for row in csvReader:
jsonArray.append(row)
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)
我转换了一个 200MB 的文件,它有 600K+ 行,效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.