open関数で開いたファイルに対しては、readメソッドを使うことで内容を読み取り、取得することができます。
readメソッド
![python read 1](https://sunagitsune.com/wp-content/uploads/2022/10/python-read-1.png)
まずopen関数を使い、ファイルを開きます。
この時、代入されているtestはファイルオブジェクトとなります。
この時、代入されているtestはファイルオブジェクトとなります。
![python read 2](https://sunagitsune.com/wp-content/uploads/2022/10/python-read-2.png)
テストファイルの中身はこんな感じ。
#python
test = open("test.txt","r")
print(test.read())
test.close
あとはread()でファイルオブジェクトを指定すると、
![python read 3](https://sunagitsune.com/wp-content/uploads/2022/10/python-read-3.png)
ファイルの中身が取得できる、という寸法です。
注意点
openとreadは一対一
![python read 4](https://sunagitsune.com/wp-content/uploads/2022/10/python-read-4.png)
一度のopenに対しreadが使えるのは一度までです。
![python read 5](https://sunagitsune.com/wp-content/uploads/2022/10/python-read-5.png)
二回openすれば二回readできます。
wは読めない
![python read 6](https://sunagitsune.com/wp-content/uploads/2022/10/python-read-6.png)
モードがw、a、xの場合、読み取りは許可されていないのでできません(モードについてはopenの記事参照)。
![](https://sunagitsune.com/wp-content/uploads/2022/05/laptop-g2651bd324_1280-160x90.png)
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。
初期準備、基本概念
ダウンロード、インストール、起動
ShellとEditor、保存、実行
保存したPythonの起動
コメント、docstring、行またぎ
コメント、...
コメント