【发布时间】:2021-10-21 08:52:08
【问题描述】:
我有以下 python 代码将 csv 文件转换为 json 文件。
def make_json_from_csv(csv_file_path, json_file_path, unique_column_name):
import csv
import json
# create a dictionary
data = {}
# Open a csv reader called DictReader
with open(csv_file_path, encoding='utf-8') as csvf:
csv_reader = csv.DictReader(csvf)
primary_key_column_name = unique_column_name.lstrip() # remove leading space in string
# Convert each row into a dictionary
# and add it to data
for rows in csv_reader:
key = rows[primary_key_column_name]
data[key] = rows
# Open a json writer, and use the json.dumps()
# function to dump data
with open(json_file_path, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
return None
上面的代码会将 CSV 文件中的所有行转换为 json 文件。我只想将最后 X 行转换为 json。
我正在使用 python v3。
【问题讨论】:
-
您使用的是哪个特定版本的 Python 3?
-
@Dani Mesejo,我正在使用 python v3.8.5
标签: python python-3.x csv