Python3 如何读写文本

实际案例

某文本文件编码格式已知(如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版本的代码如下:

Python
# -*- coding: utf-8 -*- # 打开文件 f = <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/open" title="View all posts in open" target="_blank">open</a></span>('py2.txt', 'w') s = u'你好' # 写入文件 f.write(s.encode('gbk')) # s.encode('gbk') 编码 # 关闭文件 f.close() f = <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/open" title="View all posts in open" target="_blank">open</a></span>('py2.txt', 'r') # 读入文件 t = f.read().decode('gbk') # .decode('gbk') 解码 print t f.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-
 
# 打开文件
f = open ( 'py2.txt' , 'w' )
 
s = u '你好'
# 写入文件
f . write ( s . encode ( 'gbk' ) ) # s.encode('gbk') 编码
# 关闭文件
f . close ( )
 
f = open ( 'py2.txt' , 'r' )
# 读入文件
t = f . read ( ) . decode ( 'gbk' ) # .decode('gbk') 解码
print t
 
f . close ( )

其运行结果为:

Python
你好
1
你好

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

Python
# 打开文件 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() """ rt wt 以文本的形式进行读写 """
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 打开文件
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 ( )
 
"""
rt wt 以文本的形式进行读写
 
"""


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




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值