如何读写文本文件

作者: SmallRookie | 来源:发表于2017-08-10 20:06 被阅读53次
    实际案例

    某文本文件编码格式已知(如UTF-8,GBK,BIG5),在Python 2.X和Python 3.X中分别如何读取该文件?

    解决方案:

    • Python 2.X:写入文件前对Unicode编码,读入文件后对二进制字符串编码;
    • Python 3.X:open函数指定't'的文本模式,encoding指定编码格式。

    注:
          字符串的语义发生了变化
        Python 2.X    Python 3.X
       --------------------------------------------
         str     ->   bytes
         unicode  ->   str

    Python 2.X版本的代码如下:

    # -*- coding: utf-8 -*-
    
    # 打开文件
    f = open('py2.txt', 'w')
    
    s = u'你好'
    # 写入文件
    f.write(s.encode('gbk'))
    # 关闭文件
    f.close()
    
    f = open('py2.txt', 'r')
    # 读入文件
    t = f.read().decode('gbk')
    print t
    
    f.close()
    

    其运行结果为:

    你好
    

    Python 3.X版本的代码如下:

    # 打开文件
    f = open('py3.txt', 'wt', encoding='utf8')
    # 将“你好”写入文件
    f.write('你好')
    # 关闭文件
    f.close()
    
    f = open('py3.txt', 'rt', encoding='utf8')
    # 将文件内容读入
    s = f.read()
    print(s)
    
    f.close()
    

    其运行结果与Python 2.X版本代码运行结果一致。

    相关文章

      网友评论

        本文标题:如何读写文本文件

        本文链接:https://www.haomeiwen.com/subject/lpdxrxtx.html