我正在嘗試撰寫一個程式,該程式從 JSON 檔案中獲取資料,將其放入陣列中,然后將陣列寫入 CSV 檔案以供人類閱讀。我已經在決議 JSON 檔案,陣列看起來像這樣:
sensorTest = [[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]],
[[13, 14, 15],
[16, 17, 18],
[19, 20, 21],
[22, 23, 24]]]
我希望將其寫入 CSV 檔案,以便將每個串列的元素放置在自己的列中,如下所示:所需的 CSV 輸出
相反,在我嘗試過的所有內容中,我不斷得到一些基本上只是將所有陣列元素放在第一列中的東西,如下所示:輸出錯誤
我將在下面附上我的代碼。
import json
import csv
from os import walk
from os import path
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
if __name__ == "__main__":
sensorBoard = [0, 1]
with open("./Data/sensorData.csv", "w", encoding='utf8', newline='') as csvfile:
csvfile.write("C1,C2,C3,C4,C5,C6,C7,C8\n")
hrd = csv.writer(csvfile) # hrd is human-readable data
for board in sensorBoard: # loop through element number of lists
print(board)
print(sensorTest[board])
# print(sensorTest[board][0])
# print(sensorTest[board][1])
for channelIndex, channelVals in enumerate(sensorTest[board]): # this grabs the set of values for the channel
print(sensorTest[board][channelIndex])
# hrd.writerow([str(sensorTest[board][channelIndex])])
for valIndex, val in enumerate(sensorTest[board][channelIndex]):
hrd.writerow([str(val)])
uj5u.com熱心網友回復:
讓 Python 為你做更多的作業:
data = sensorTest[0] sensorTest[1]
with open("output.csv", "w", encoding='utf8') as csvfile:
hrd = csv.writer(csvfile)
hrd.writerow(["C%d"%d for d in range(1,1 len(data))])
for r in zip(*data):
hrd.writerow(r)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/495901.html
