我正在嘗試將 Json 檔案轉換為 Csv
我無法建立邏輯。這是我試過的
代碼
import json
import csv
import os
with open('truck_trips.json') as json_file:
data = json.load(json_file)
file_path = 'json_data.csv'
if not os.path.exists(file_path):
print("No File")
header = ['Truck_Id', 'Trip_Id', 'Start', 'End']
with open(file_path, 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
for item in data:
print(item)
for t in data[item]:
print(t)
print(data[item][t])
print("\n")
uj5u.com熱心網友回復:
這完成了作業,
# Getting the JSON content.
with open("/content/truck_trips.json", "r") as f:
json_output = f.read()
output_dict = json.loads(json_output)
# Storing the relevant data from the JSON file into a list.
trucks_detail = []
for truck in output_dict:
for trip in output_dict[truck]:
trips = output_dict[truck][trip]
for i in range(len(trips)):
start, end = trips[i][0], trips[i][1]
truck_detail = [truck, f"{trip}.{i 1}", start, end]
trucks_detail.append(truck_detail)
# Converting it into a dataframe.
df = pd.DataFrame(trucks_detail, columns = ["Truck_Id", "Trip_Id", "Start", "End"])
df.to_csv("Truck Details.csv", index = False)
資料框,
| Truck_Id | Trip_Id | 開始 | 結尾 | |
|---|---|---|---|---|
| 0 | 卡車_1 | trip_1.1 | 多倫多 | 基奇納 |
| 1 | 卡車_1 | trip_1.2 | 基奇納 | 科堡 |
| 2 | 卡車_1 | trip_1.3 | 科堡 | 艾爾默 |
| 3 | 卡車_1 | trip_1.4 | 艾爾默 | 歐文桑德 |
| 4 | 卡車_1 | trip_1.5 | 歐文桑德 | 奧里利亞 |
| 5 | 卡車_1 | trip_1.6 | 奧里利亞 | 多倫多 |
| 6 | 卡車_1 | trip_2.1 | 多倫多 | 渥太華 - 加蒂諾 |
| 7 | 卡車_1 | trip_2.2 | 渥太華 - 加蒂諾 | 韋蘭 - 佩勒姆 |
| 8 | 卡車_1 | trip_2.3 | 韋蘭 - 佩勒姆 | 多倫多 |
| 9 | 卡車_1 | trip_3.1 | 多倫多 | 弗朗西絲堡 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464539.html
