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))
xlsx文件存储
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["我", "你", "她"])
wb.save(filename="data.xlsx")
from openpyxl import load_workbook
wb = load_workbook(filename="data.xlsx")
sheets = wb.get_sheet_names()
sheet_first = sheets[0]
ws = wb.get_sheet_by_name(sheet_first)
rows = ws.rows
columns = ws.columns
for row in rows:
line = [col.value for col in row]
print(line)
for column in columns:
line = [ro.value for ro in column]
print(line)
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)