如何在 Python 中读取 Unicode 编码的文本文件?

以下代码展示了如何读取 Unicode 编码的文本文件:

for txt_file in os.listdir(os.path.join(dir_path, folder)):
    if not txt_file.endswith('.pci'):  # 如果该文件不是pci文件,则跳过
        continue

    file_path = os.path.join(dir_path, folder, txt_file)  # 拼接出pci文件的全路径

    # 打开pci文件并读取内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
        # 对文件内容进行处理

解释:

  • 将文件打开模式从 'rb'(二进制模式)改为 'r'(文本模式)。
  • 使用 encoding='utf-8' 参数指定文件编码格式为 UTF-8。

通过以上修改,代码可以正确读取 Unicode 编码的文本文件。

注意:

  • 确保你的文件实际编码格式与你指定的 encoding 参数一致,否则可能会出现乱码问题。
  • 如果你的文件编码格式不确定,可以使用 chardet 库来检测文件编码。
Python 读取 Unicode 编码文本文件:使用 'encoding' 参数

原文地址: https://www.cveoy.top/t/topic/lQ3r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录