Python 读取 txt 文件

短命女 2021-09-24 04:44 603阅读 0赞

文章目录

    1. 准备
    1. 代码
    1. 结果
    1. 说明

1. 准备

文件名为 “info.txt”,
文件内容如下:

欢迎学习Python语言
第一章:Python前世今生
第二章:Python语言基础
第三章:Python高级进阶

2. 代码

  1. text_file = open('info.txt', 'rt', encoding='utf-8')
  2. for line in text_file.readlines():
  3. print(line, end='')
  4. text_file.close()

  1. text_file = open('info.txt', 'rt', encoding='utf-8')
  2. content = text_file.read()
  3. print(content)
  4. text_file.close()

  1. with open('info.txt', 'rt', encoding='utf-8') as text_file:
  2. content = text_file.read()
  3. print(content)

  1. with open('info.txt', 'rt', encoding='utf-8') as text_file:
  2. for line in text_file.readlines():
  3. print(line, end='')

3. 结果

with open 运行结果

4. 说明

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

发表评论

表情:
评论列表 (有 0 条评论,603人围观)

还没有评论,来说两句吧...

相关阅读