1. 准备
文件名为 “info.txt”,
文件内容如下:
欢迎学习Python语言
第一章:Python前世今生
第二章:Python语言基础
第三章:Python高级进阶
2. 代码
text_file = open('info.txt', 'rt', encoding='utf-8')
for line in text_file.readlines():
print(line, end='')
text_file.close()
或
text_file = open('info.txt', 'rt', encoding='utf-8')
content = text_file.read()
print(content)
text_file.close()
或
with open('info.txt', 'rt', encoding='utf-8') as text_file:
content = text_file.read()
print(content)
或
with open('info.txt', 'rt', encoding='utf-8') as text_file:
for line in text_file.readlines():
print(line, end='')
3. 结果
4. 说明
在我的环境下,如果不加参数,“encoding=utf-8”,会报错。
错误内容是:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xad in position 20: illegal multibyte sequence