温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用python读取utf-8编码格式的文本文件

发布时间:2021-11-20 15:12:10 来源:亿速云 阅读:1587 作者:iii 栏目:编程语言

本篇内容介绍了“怎么用python读取utf-8编码格式的文本文件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

# 读取utf-8编码格式的文本文件 
# 这里Python解释器读取的是utf-8编码的字节流,然后再按指定的编码方式解释这些字节流
# 这样就比较好理解乱码的原因


#coding=utf-8   
# When Python reads the encoding it tries to interpret the file as utf-8 
# 告诉Python解释器编译时采用哪种编码方式
# 如未设置编码方式,且解释器可识别文件(如utf-8编码格式的文件有的(与编辑器有关)带有BOM,可供解释器识别)编码方式则采用文件编码方式,反之采用终端默认编码方式


import sys
# reload(sys)
# 指定终端默认编码方式
# sys.setdefaultencoding('utf8')
# 获取终端默认编码方式
# sys.getdefaultencoding()


import codecs
def ConvertCN(s):
    if s[:3] == codecs.BOM_UTF8:
        s = s[3:]
        
    # 若系统默认编码方式为acsii且未修改默认编码方式 
    # s.encode('gbk'):s(文件编码格式)--(.decode('ascii'))-->unicode--(.encode('gbk'))-->s(gbk编码格式) (这个过程由终端完成,未指定编码方式时将采用终端默认编码方式)
    # 兼容关系:ASCII --> ISO-8859-1 --> UNICODE(UTF-8,UTF-16,UTF-32) --> UCS(UCS2[与UNICODE兼容],UCS4), ASCII --> GB2312 --> GBK --> GB18030
    # 因utf-8向下兼容ascii ascii不向上兼容utf-8,对此处s(utf-8编码格式)进行ascii解码成unicode时可能发生错误
    return s.decode('utf-8')


def PrintFile(filename):
    f = file(filename,'r')
    for f_line in f.readlines():
        print ConvertCN(f_line)
    f.close()
    
if __name__ == "__main__":
    
    PrintFile('OperCodingFile.txt')
    
    # Python输出的是字节流 打印由终端处理
    # print 在终端显示如何是由终端决定的
    """
    它大致讲解下python中的print原理: 
    When Python executes a print statement, 
    it simply passes the output to the operating system (using fwrite() or something like it), 
    and some other program is responsible for actually displaying that output on the screen. 
    For example, on Windows, it might be the Windows console subsystem that displays the result. 
    Or if you're using Windows and running Python on a Unix box somewhere else, 
    your Windows SSH client is actually responsible for displaying the data. 
    If you are running Python in an xterm on Unix, then xterm and your X server handle the display. 
    To print data reliably, you must know the encoding that this display program expects. 
    简单地说,python中的print直接把字符串传递给操作系统,所以你需要把str解码成与操作系统一致的格式。
    Windows使用CP936(几乎与gbk相同),所以这里可以使用gbk。
    """
    
    print ConvertCN("\n****** 按任意键退出!*******")  
    
    sys.stdin.readline()

“怎么用python读取utf-8编码格式的文本文件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI