Python を使用してテキスト ドキュメントを読み取る方法は 4 つあります。 ファイル コンテンツ全体を直接読み取る ファイル コンテンツを 1 行ずつ読み取り、リストに保存する ファイル コンテンツを 1 行ずつ繰り返し実行する エンコーディング、読み取りモード、およびファイルの改行 シンボルとその他のオプションのパラメーター

Python を使用してテキスト ドキュメントを読み取る方法
直接メソッド:
<code class="python">with open("filename.txt", "r") as f:
contents = f.read()</code>#1 行ずつ読み取る:
<code class="python">with open("filename.txt", "r") as f:
lines = f.readlines()</code><code class="python">with open("filename.txt", "r") as f:
for line in f:
# 对每一行进行操作</code>
「example.txt」という名前のファイルを読み取り、その内容を出力します:
<code class="python">with open("example.txt", "r") as f:
contents = f.read()
print(contents)</code>Read "example .txt"ファイルを作成してリストに保存します:
<code class="python">with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)</code>「example.txt」ファイルを 1 行ずつ読み取り、各行を出力します:
<code class="python">with open("example.txt", "r") as f:
for line in f:
print(line)</code>以上がPythonでテキストドキュメントを読む方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。