python open ansi_python文件格式转换ansi文本转utf8

处理ansi编码转utf8

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

# @Author : kinggoo

# @Software: 鳗鱼是条狗

# @blog :https://kinggoo.com/pyansitoutf8.htm

import os

import sys

import time

import codecs

import chardet

"""

主要是GB2312转utf-8格式,其他格式可以通过chardet来获取类型转换。

kinggoo.com

"""

if __name__=="__main__":

file_path = "./txt"

file_path_new = "./txtnew"

files = os.listdir(file_path)

for file in files:

file_name = file_path + '/' + file

# 不重复

if os.path.isfile(file_path_new + '/' + file):

print("已存在文件 %s"%file_path_new + '/' + file)

continue

f_2 = open(file_name, 'rb') # 注意此处打开方式 'rb'

str_1 = f_2.readline()

chardet_1 = chardet.detect(str_1)

print("编码为:%s"%chardet_1)

if chardet_1['encoding'] == 'GB2312':

f = codecs.open(file_name, 'r', 'ansi')

ff = f.read()

file_object = codecs.open(file_path_new + '/' + file, 'w', 'utf-8')

file_object.write(ff)

else:

print("文件:%s 格式:%s"%(file_name,chardet_1['encoding']))

- THE END -

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UTF-8是一种可变长度的Unicode编码方式,而ANSI是一种字符编码方式。要将UTF-8格式转换ANSI格式,需要使用特定的工具或编程语言来实现。 在Python中,可以使用编码函数来实现UTF-8换为ANSI。首先,我们需要读取以UTF-8编码的文件或字符串,并指定编码为'utf-8'。然后,我们将其使用编码函数进行换并指定目标编码为'ansi'。 以下是一个示例代码: ```python # 导入codecs模块 import codecs # 以UTF-8编码读取文件内容 with codecs.open('input.txt', 'r', 'utf-8') as file: utf8_content = file.read() # 将UTF-8换为ANSI编码 ansi_content = utf8_content.encode('ansi') # 将ANSI内容写入新文件 with codecs.open('output.txt', 'w', 'ansi') as file: file.write(ansi_content) ``` 在上面的示例中,我们首先使用'codecs.open'函数以'utf-8'编码读取名为'input.txt'的文件内容,并将其存储在变量'utf8_content'中。然后,我们使用编码函数'encode'将'utf8_content'换为ANSI编码的内容,并将结果存储在变量'ansi_content'中。最后,我们将'ansi_content'使用'codecs.open'函数以'ansi'编码写入名为'output.txt'的新文件中。 请注意,在进行编码换时,可能会出现字符无法完全换或出现乱码的情况。这是因为ANSI编码方式可能无法表示UTF-8中某些特殊字符或语言特定的字符。因此,在换编码时,需要确认目标编码是否支持源内容中使用的所有字符。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值