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
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)
複製代碼