テキストファイルを読み取る
プログラム
file_path = "example.txt"
# ファイルを読み取りモードで開く
with open(file_path, "r") as file:
# ファイルの内容を読み取る
content = file.read()
print(content)
実行結果
以下のように、This is a reading test.と書かれたexample.txtというテキストファイルを用意しました。
![](https://engineer-index.com/wp-content/uploads/2024/04/image.png)
以下のように、テキストファイルの内容を読み込みprint関数で出力できています。
![](https://engineer-index.com/wp-content/uploads/2024/04/image-1.png)
テキストファイルに書き込む
プログラム
file_path = "example.txt"
# ファイルを書き込みモードで開く
with open(file_path, "w") as file:
# ファイルに書き込む
file.write("Hello, world!\n")
file.write("This is a written test.")
実行結果
![](https://engineer-index.com/wp-content/uploads/2024/04/image-3.png)
テキストをファイルに書き込めました。
テキストファイルに追記する
プログラム
file_path = "example.txt"
# ファイルを追記モードで開く
with open(file_path, "a") as file:
# ファイルに追記する
file.write("\nAppending new line.")
実行結果
![](https://engineer-index.com/wp-content/uploads/2024/04/image-4.png)
上の「テキストファイルに書き込む」で作成したファイルに追記を行うことができました。
コメント