import chardet
import pandas as pd
# 指定文件路径
file_path = "你的文件名.csv"
# 读取部分数据检测编码
def detect_encoding(file_path, sample_size=100000):
with open(file_path, "rb") as f:
rawdata = f.read(sample_size) # 读取前100KB
result = chardet.detect(rawdata) # 检测编码
return result["encoding"]
# 获取检测到的编码
detected_encoding = detect_encoding(file_path)
print(f"检测到的编码格式: {detected_encoding}")
# 使用检测到的编码读取 CSV 文件
try:
df = pd.read_csv(file_path, encoding=detected_encoding)
print("文件读取成功!")
except Exception as e:
print(f"读取 CSV 文件时出错: {e}")
# 显示数据前几行
print(df.head())
确定好文件格式以后,选择相对于的格式来读取文件,避免UTF-8的错误
# 上传文件
file_path = "water_quality_data_with_dates.csv"
# 读取数据,使用检测到的GB2312编码(仅做一个例子)
df = pd.read_csv(file_path, encoding="GB2312")