Python 尝试将csv的第1-10行移动到JSON文件。我好像只有第十行
我是python新手,尝试将csv的第1-10行添加到JSON文件中,但是,我似乎只得到了csv的第10行。我似乎不明白我的论点有什么不正确之处。创建任何帮助应用程序Python 尝试将csv的第1-10行移动到JSON文件。我好像只有第十行,python,python-3.x,Python,Python 3.x,我是python新手,尝试将csv的第1-10行添加到JSON文件中,但是,我似乎只得到了csv的第10行。我似乎不明白我的论点有什么不正确之处。创建任何帮助应用程序 import csv, json, itertools csvFilePath = "example.csv" jsonFilePath = "example.json" # Read the CSV and add data to a dictionary data = {} with open(csvFilePat
import csv, json, itertools
csvFilePath = "example.csv"
jsonFilePath = "example.json"
# Read the CSV and add data to a dictionary
data = {}
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
for csvRow in itertools.islice(csv.DictReader(csvFile), 0,10):
data = csvRow
print(data)
#Write the data to a JSON file
with open(jsonFilePath, "w") as jsonFile:
jsonFile.write(json.dumps(data, indent=4))
在
data=csvRow
时,data
变量不断被覆盖,因此在末尾,只有您读取的最后一行将位于data
内。试着这样做:
import csv, json, itertools
csvFilePath = "example.csv"
jsonFilePath = "example.json"
# Read the CSV and add data to a dictionary
data = {}
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
for csvRow in itertools.islice(csv.DictReader(csvFile), 0,10):
#email = csvRow["email"]
data[len(data)] = csvRow
print(data)
# Write the data to a JSON file
with open(jsonFilePath, "w") as jsonFile:
jsonFile.write(json.dumps(line, indent=4))
(没有对此进行测试,但想法是添加
csvRow
作为dict数据的新元素)假设输入CSV为
1,2,3,4,5
a,b,c,d,e
我们有以下代码:
import json
import csv
inpf = open("test.csv", "r")
csv_reader = csv.reader(inpf)
# here you slice the columns with [2:4] for example
lines = [row[2:4] for row in csv_reader]
inpf.close()
lines_json = json.dumps(lines)
outpf = open("out.json", "w")
outpf.write(lines_json)
outpf.close()
这创造了
[
[
"3",
"4"
],
[
"c",
"d"
]
]
您正在覆盖文件循环中的数据
字典
CSV_FILE_PATH = "example.csv"
with open(CSV_FILE_PATH) as myfile:
# You might set a key for each index as you loop:
data = {i: next(myfile) for i in range(10)}
print(data)