当前位置: 首页 > news >正文

不绕弯地解决文件编码问题,锟斤拷烫烫烫

安装python对应库

 pip install chardet

检测文件编码

import chardet

# 检测文件编码
file_path = r'C:\Users\AA\Desktop\log.log' # 这里放文件和文件绝对路径
with open(file_path, 'rb') as f:
    raw_data = f.read(100000)  # 读取前10000个字节
    result = chardet.detect(raw_data)
    encoding = result['encoding']
    confidence = result['confidence']
    print(f"检测到的编码: {encoding}, 置信度: {confidence}")

使用检测到的编码读取文件

# 使用检测到的编码读取文件
detected_encoding = 'GB2312'  # 替换为检测到的编码
output_file_path = r'C:\Users\AA\Desktop\log_fixed.txt' # 这里写输出的文件的路径

try:
    with open(file_path, 'r', encoding=detected_encoding, errors='ignore') as f:
        text = f.readlines()

    with open(output_file_path, 'w', encoding='utf-8') as f:
        f.writelines(text)

    print("文件编码转换完成,已保存为 log_fixed.txt。")
except Exception as e:
    print(f"处理过程中出现错误: {e}")

用jupyter运行结果如下

相关文章:

  • 将java生成dex并通过app_process执行的教程
  • 视频深度估计部署测评
  • Java实战报错
  • 【笔记】为什么Cholesky Decomposition和Rotation-Scaling Decomposition可以解决协方差矩阵正半定性问题?
  • 网管平台核心功能解析(八)——端口下联
  • 红宝书第二十九讲:详解编辑器和IDE:VS Code与WebStorm
  • Lua环境搭建+Lua基本语法
  • OpenCV 图形API(13)用于执行两个矩阵(或图像)逐元素乘法操作的函数mul()
  • (八)图像视图
  • 使用LangGraph构建多代理Agent、RAG
  • WHAT - Electron 系列(一)
  • 第十八章:Python实战专题:北京市水资源数据可视化与图书馆书籍管理应用开发
  • C++ | 函数模板
  • CAD插件实现:自动递增编号(前缀、后缀、位数等)——CADc#实现
  • 配置文件 yaml
  • Unity2D:从零开始制作一款跑酷游戏!
  • 【第2月 day16】Matplotlib 散点图与柱状图
  • 第四课:模型的概念及应用
  • 【trino】trino配置证书https tls/ssl访问
  • Git -> git pull --rebase 遇到error : Filename too long的临时解决方案