python - Python CSV转JSON批量查询,如何输出剩余项
问题描述
好的,标题有点混乱,所以我很抱歉。
基本上,我正在编写一个 Python 脚本,它只是从 CSV 文件的内容创建一个新的 JSON 文件。
在大多数情况下,该脚本有效,但现在我处于需要进行 tweeking 的部分。
现在,我已经设置好了,它会读取内容,并为 CSV 文件中的每 10 个项目创建一个文件。
import csv
import json
from time import time
start = time()
def make_json(csv_path):
data = []
with open(csv_path, encoding='utf-8-sig') as csvp:
csv_reader = csv.DictReader(csvp)
counter = 0
for row in csv_reader:
row_items = list(row.items())
for k, v in row_items:
if v == "":
del row[k]
data.append(row)
counter += 1
if counter % 10 == 0:
output = {
"items": data
}
json_path = rf'test{counter}.json'
with open(json_path, 'w', encoding='utf-8-sig') as jsonp:
jsonp.write(json.dumps(output, indent=2))
counter += 0
data = []
csv_path = r'random43.csv'
make_json(csv_path)
print(f'Time taken to run: {time() - start} seconds')
CSV 示例:
Number,First Name,Last Name
1,Marion,Maltie
2,Jesse,Christopher
3,Frank,Dixon
4,Marquerite,Holbrook
5,Justin,Houk
6,Annette,Root
7,Noreen,Marshall
8,Kathryn,Griggs
9,Tammy,Dana
10,Nicholas,Richardson
11,Katherine,Wilks
12,Jessica,Phillips
13,Alan,Woodward
这很好用……如果 CSV 文件中只有 10 的倍数的项目。现在的问题是如何处理剩余的项目。
例如,包含 40 个项目的 CSV 将踢出四个文件;第一个 10,第二个 20,依此类推。但是,如果我运行包含 43 个项目(或任何不以零结尾的项目)的 CSV,它仍然只会推出四个文件。文件中的最后三个项目将被简单地忘记。
我正在自杀,试图弄清楚如何将最后几项放在他们自己的较小文件中。任何帮助我朝着正确的方向前进将不胜感激!!
解决方案
除了在循环期间写入 10 的倍数之外,您还需要在完成循环后将剩余项目写入输出文件。
for row in csv_reader:
# do something with row
# collect items in data
# data.append(something)
counter += 1
if counter % 10 == 0:
# write output to file
data = []
# for loop ended
# If data is not empty, we have remaining items to write
if data:
# write output to file
首先,让我们创建一个名为write_json()
. 例如:
def write_json(path, data):
output = {"items": data}
with open(json_path, 'w', encoding='utf-8-sig') as jsonp:
json.dump(jsonp, output, indent=2)
然后使用我们刚刚在代码中定义的函数:
def make_json(csv_path):
data = []
with open(csv_path, encoding='utf-8-sig') as csvp:
csv_reader = csv.DictReader(csvp)
counter = 0
for row in csv_reader:
row_items = list(row.items())
for k, v in row_items:
if v == "":
del row[k]
data.append(row)
counter += 1
if counter % 10 == 0:
json_path = rf'test{counter}.json'
write_json(json_path, data)
data = []
if data:
json_path = rf'test{counter}.json'
write_json(json_path, data)