Pythonはtxtファイルを読み取ります

記事ディレクトリ

1.準備

ファイル名は「info.txt」
で、ファイル内容は次のとおりです。

Python言語の学習へようこそ
第1章:Pythonの過去と現在
第2章:Python言語の基本
第3章: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'コーデックは位置20のバイト0xadをデコードできません:不正なマルチバイトシーケンス

おすすめ

転載: blog.csdn.net/PursueLuo/article/details/105704219