系统:Windows 7
语言版本:Anaconda3-4.3.0.1-Windows-x86_64
编辑器:pycharm-community-2016.3.2
- 这个系列讲讲codecs模块常用功能
- 本文介绍:读取文件
Part 1:代码
import os
import codecs
current_address = os.path.dirname(os.path.abspath(__file__))
file_address = os.path.join(current_address, "三国演义.txt")
fil = codecs.open(file_address, mode='r', encoding='utf-8')
lines = [line.strip() for line in fil]
fil.close()
for line in lines:
print(line)
代码截图
1.png
输出:
2.png
Part 2:部分代码解读
-
codecs.open(file_address, mode='r', encoding='utf-8'),读取文本文件- 编码方式是
utf-8,如果去掉,则会报错,如下图 - 去掉
utf-8,读取另外一个文件,不会报错
- 编码方式是
报错
3.png
不报错
4.png
这是为啥呢?
今天有点晚了,欢迎读者来答,其实我也不是特别清晰,哈哈
本文为原创作品,欢迎分享朋友圈
常按图片识别二维码,关注本公众号
Python 优雅 帅气
12x0.8.jpg















网友评论