Python 读取 txt 文件

文章目录

  • 1. 准备
  • 2. 代码
  • 3. 结果
  • 4. 说明

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

Python 读取 txt 文件_第1张图片

4. 说明

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

你可能感兴趣的:(Python)