1、背景介绍
我们再日常读取csv文件的时候经常会发现csv文件的格式有多种,常见的有【utf-8】\【gbk】\ 【ansi】格式,我们再读取的时候会加上encoding="xx"参数,为了,方便我们可以使用 chardet.detect()检测文件编码。
- 编码检测:通过chardet自动检测文件编码,确保正确读取文件内容。
- 异常处理:对可能出现的编码错误进行处理,提供备用的utf-8编码读取方案。
- csv处理:使用标准库csv模块读取并打印csv文件内容,包括表头和数据行。
2、库的安装
库 | 用途 | 安装 |
---|---|---|
csv | csv文件的读写 | 内置库无需安装 |
3、核心代码
①:到的编码格式
def detect_encoding(file_path): with open(file_path, 'rb') as f: raw_data = f.read() result = chardet.detect(raw_data) return result['encoding']
②:调用detect_encoding函数获取文件的编码格式
def main(): file_path = '新建xlsx 工作表.csv' encoding = detect_encoding(file_path) try: read_csv(file_path, encoding) except unicodedecodeerror: # 如果检测到的编码格式读取失败,尝试使用 utf-8 编码读取 try: read_csv(file_path, 'utf-8') except exception as e: print(f"读取文件时发生错误: {e}") except exception as e: print(f"读取文件时发生错误: {e}")
4、完整代码
# -*- coding: utf-8 -*- ''' @project :测试 @file :test2_read_csv.py @ide :pycharm @author :一晌小贪欢(278865463@qq.com) @date :2025/3/1 21:40 ''' import csv import chardet def detect_encoding(file_path): with open(file_path, 'rb') as f: raw_data = f.read() result = chardet.detect(raw_data) return result['encoding'] def read_csv(file_path, encoding): with open(file_path, 'r', encoding=encoding) as f: reader = csv.reader(f) head = next(reader) print("表头", head) for row in reader: print(row) def main(): file_path = '新建xlsx 工作表.csv' encoding = detect_encoding(file_path) try: read_csv(file_path, encoding) except unicodedecodeerror: # 如果检测到的编码格式读取失败,尝试使用 utf-8 编码读取 try: read_csv(file_path, 'utf-8') except exception as e: print(f"读取文件时发生错误: {e}") except exception as e: print(f"读取文件时发生错误: {e}") if __name__ == "__main__": main()
到此这篇关于python如何实现读取csv文件时忽略文件的编码格式的文章就介绍到这了,更多相关python读取csv内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论