Python 读取 txt 文件

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. 结果

with open 运行结果

4. 说明

在我的环境下,如果不加参数,“encoding=utf-8”,会报错。
错误内容是:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xad in position 20: illegal multibyte sequence

猜你喜欢

转载自blog.csdn.net/PursueLuo/article/details/105704219