网站建设的基本要素有,wordpress手动安装,网站建设课程的感受,福州建设网站效果图背景
最近在做数据的训练#xff0c;经常需要读取写入csv、xlsx、json文件来获取数据#xff0c;在这里做简单总结记录。
ps: 读取和写入中文文件时#xff0c;需要确保文件的编码格式是正确的。通常情况使用UTF-8编码格式。如果使用其他编码格式可能会导致读取或写入时出…背景
最近在做数据的训练经常需要读取写入csv、xlsx、json文件来获取数据在这里做简单总结记录。
ps: 读取和写入中文文件时需要确保文件的编码格式是正确的。通常情况使用UTF-8编码格式。如果使用其他编码格式可能会导致读取或写入时出现乱码问题。
实操
csv
读取
import csv with open(file.csv, r, encodingutf-8) as csv_file: reader csv_file.readlines() 写入
import csv data [[, ],] with open(output.csv, w, newline, encodingutf-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 pddata {表头1: [, , ],表头2: [, , ]}
df pd.DataFrame(data)
df.to_excel(output.xlsx, indexFalse)
json
读取
import json with open(file.json, r) as json_file: data json.load(json_file)# 打印 JSON 数据 缩进2空格
print(json.dumps(data, indent2))
写入
import json data [{: ,}] with open(output.json, w) as file: for item in data:json.dump(item, file, ensure_asciiFalse)