将csv的最后X行转换为json



我有以下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.6+中,字典保持插入顺序,所以要获取字典的最后一行,只需执行:

from itertools import islice
x = 5
d = {}
for i, v in enumerate("abcdedfghi"):
d[i] = v
d = dict(islice(d.items(), len(d) - x, len(d)))
print(d)

{5: 'd', 6: 'f', 7: 'g', 8: 'h', 9: 'i'}

基本上是在你的代码中添加(更改)这些行:

from itertools import islice
x = 5
data = dict(islice(data.items(), len(data) - x, len(data)))
# 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))

我想根据Dani Mesejo的回答来回答我自己的问题。这完全是他的功劳。

def make_json(csv_file_path, json_file_path,
unique_column_name, no_of_rows_to_extract):
import csv
import json
from itertools import islice
# 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
data = dict(islice(data.items(), len(data) - no_of_rows_to_extract, len(data)))
# 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

最新更新