背景
最近在做数据的训练,经常需要读取写入csv、xlsx、json文件来获取数据,在这里做简单总结记录。
ps: 读取和写入中文文件时,需要确保文件的编码格式是正确的。通常情况使用UTF-8编码格式。如果使用其他编码格式可能会导致读取或写入时出现乱码问题。
实操
csv
读取
import csv
with open('file.csv', 'r', encoding='utf-8') as csv_file:
reader = csv_file.readlines()
写入
import csv
data = [['', ''],]
with open('output.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
for row in data:
writer.writerows(row)
xlsx
读取
import pandas as pd
data = pd.read_excel('file.xlsx')
data = data.values
写入
import pandas as pd
data = {'表头1': ['', '', ''],
'表头2': ['', '', '']}
df = pd.DataFrame(data)
df.to_excel('output.xlsx', index=False)
json
读取
import json
with open('file.json', 'r') as json_file:
data = json.load(json_file)
# 打印 JSON 数据 缩进2空格
print(json.dumps(data, indent=2))
写入
import json
data = [{'': '',}]
with open('output.json', 'w') as file:
for item in data:
json.dump(item, file, ensure_ascii=False)