我有以下 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。
uj5u.com熱心網友回復:
在 Python 3.6 中,dict 保持插入順序,因此要獲取字典的最后一行,只需執行以下操作:
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))
uj5u.com熱心網友回復:
我想以 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329213.html
下一篇:如何在許多標簽中找到?(美湯)
