Python read関数でファイルの中身を全て取得する

環境
Python 3.9.13
Windows 10 Home 64bit
PyCharm 2022.2.1 (Community Edition)

構文
with open('ファイル名’, 'r’) as file:
file.read()
read()関数を使ってファイル内のデータを全て読み込んでいます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
with open('123.txt', 'r') as file:
# すべて取得する
res = file.read()
print(res)
with open('123.txt', 'r') as file: # すべて取得する res = file.read() print(res)
 with open('123.txt', 'r') as file:
      # すべて取得する
      res = file.read()

print(res)

結果
yamada tokyo

Python

Posted by arkgame