如何读写文本文件

来源:互联网 发布:淘宝宝贝照片拍摄 编辑:程序博客网 时间:2024/05/22 09:47
实际案例

某文本文件编码格式已知(如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 tf.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版本代码运行结果一致。