[英]Only writing first line to CSV - don't understand why
I need to convert multiple JSON file to a CSV file. 我需要将多个JSON文件转换为CSV文件。 I have a data.zip folder that contains 2000 .JSON file.
我有一个data.zip文件夹,其中包含2000个.JSON文件。 I am able to load the JSON file and print the data inside each JSON file with print normalized.
我能够加载JSON文件并使用标准化的打印功能打印每个JSON文件中的数据。 But when I write it to CSV it only shows 1 line of data.
但是,当我将其写入CSV时,它仅显示1行数据。 How do I write all the .JSONS data tot he CSV file.
如何将所有.JSONS数据写入CSV文件。
import zipfile
from pandas.io.json import json_normalize
def get_text():
with zipfile.ZipFile("data.zip", "r") as z:
for filename in z.namelist():
with z.open(filename) as f:
data = json.load(f)
normalized = json_normalize(data)
print normalized
normalized.to_csv('data.csv', encoding="utf-8-sig")
Default for .to_csv is to write a new file. .to_csv的默认值是写入新文件。 You need to append - mode='a'.
您需要附加-mode ='a'。 See:
看到:
As some people explained you're overwriting your CSV file instead of appending it. 正如某些人解释的那样,您覆盖的是CSV文件,而不是附加文件。 Try appending and only writing headersThe first time around.
尝试追加并仅写标题。
Here's an example: 这是一个例子:
def get_text():
add_csv_header = True
with zipfile.ZipFile("data.zip", "r") as z:
for filename in z.namelist():
with z.open(filename) as f:
data = json.load(f)
normalized = json_normalize(data)
print normalized
normalized.to_csv('data.csv', encoding="utf-8-sig", mode='a', header=add_csv_header)
add_csv_header = False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.