Python3實現數據存儲爲json與csv

json文件存儲

import json
# 讀
with open('data.json', 'r', encoding='utf-8') as fp:
    data = json.loads(fp.read())
# 寫,且具有縮進與中文顯示
with open('data.json', 'w', encoding='utf-8') as fp:
    fp.write(json.dumps(data, indent=2, ensure_ascii=False))
複製代碼

cvs文件存儲

import csv

# 寫入, 方法一(追加用a):
# 參數newline,防止行與行之間多處空行;想修改列與列之間的分隔符,能夠傳入delimiter參數
with open('data.csv', 'w', encoding='utf-8', newline='') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    writer.writerow(['id', 'name', 'age'])
    writer.writerow(['1001', 'aici', '22'])
    writer.writerow(['1002', 'iicey', '24'])
    writer.writerow(['1003', 'ice', '18'])
# 寫入, 方法二(二維列表):
with open('data.csv', 'w', encoding='utf-8', newline='') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    writer.writerow(['id', 'name', 'age'])
    writer.writerows([['1001', 'aici', '22'], ['1002', 'iicey', '24'], ['1003', 'ice', '18']])
# 寫入, 方法三(字典):
with open('data.csv', 'w', encoding='utf-8', newline='') as csv_file:
    fieldnames = ['id', 'name', 'age']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'id': '1001', 'name': 'aici', 'age': '22'})
    writer.writerow({'id': '1002', 'name': 'iicey', 'age': '24'})
    writer.writerow({'id': '1003', 'name': 'ice', 'age': '18'})

# 讀取, 方法一:
import csv
with open('data.csv', 'r', encoding='utf-8', newline='') as csv_file:
    reader = csv.reader(csv_file)
    print(list(reader))
# 讀取, 方法二:
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
複製代碼
相關文章
相關標籤/搜索