【打开任意编码格式文件】

本文介绍了如何使用Python标准库和第三方库如chardet来读取并转换不同编码格式的文件,包括`read_file_with_encoding`和`convert_encoding_to_utf8`函数,以及`open_file`和`convert_to_utf8`函数的示例应用。
摘要由CSDN通过智能技术生成

一,使用标准库实现

import codecs

def read_file_with_encoding(filename):
    with open(filename, 'rb') as f:
        raw_data = f.read()
    file_encoding = 'utf-8'
    try_encodings = ['utf-8', 'gbk', 'big5', 'utf-16', 'latin1']
    for encoding in try_encodings:
        try:
            decoded_data = raw_data.decode(encoding)
            file_encoding = encoding
            break
        except UnicodeDecodeError:
            pass
    content = raw_data.decode(file_encoding)
    return content, file_encoding

def convert_encoding_to_utf8(source_file, target_file):
    with open(source_file, 'rb') as f:
        raw_data = f.read()
    try_encodings = ['utf-8', 'gbk', 'big5', 'utf-16', 'latin1']
    for encoding in try_encodings:
        try:
            decoded_data = raw_data.decode(encoding)
            new_data = decoded_data.encode('utf-8')
            with open(target_file, 'wb') as f:
                f.write(new_data)
            break
        except UnicodeDecodeError:
            pass

# 示例用法
content, encoding = read_file_with_encoding('test.txt')
print(content, encoding)

convert_encoding_to_utf8('test.txt', 'test_utf8.txt')

二,使用第三方库

import chardet

def open_file(file_path):
    with open(file_path, 'rb') as file:
        content = file.read()
        result = chardet.detect(content)
        encoding = result['encoding']
    return content, encoding

def convert_to_utf8(file_path, new_file_path='utf8_file.txt'):
    with open(file_path, 'rb') as file:
        content = file.read()
        result = chardet.detect(content)
        encoding = result['encoding']
    if encoding != 'utf-8':
        with open(new_file_path, 'wb') as new_file:
            new_content = content.decode(encoding).encode('utf-8')
            new_file.write(new_content)
            return new_file_path
    else:
        return "File is already in utf-8 encoding"

# 示例
file_content, file_encoding = open_file('sample_file.txt')
print(file_content, file_encoding)

new_file_path = convert_to_utf8('another_file.txt')
print(new_file_path)
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xfDenny

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值