0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

個人的な備忘録:Python の open() を使ったファイル操作(読み書き)を実装し、アウトプットしてみた

Posted at

はじめに

このプログラムは、Python を使ってシンプルなメモ帳機能を実装したものです。

ユーザーがメモを入力してファイルに保存し、後でそのメモを読み取ることができます。

ファイルの基本的な読み書きを学ぶのに適しており、Python の open() を活用した実装になっています。

書こうと思ったきっかけ

Python でのファイル操作を学ぶ際、実際に手を動かしてコードを書くことが大切だと考えました。

メモ帳のようなシンプルなプログラムなら、ファイルの読み書きを直感的に理解しやすいと思い、今回のコードを作成しました。

また、try-except を使ったエラーハンドリングの練習にもなるため、実践的な学習ができると考えました。

完成したコード

test.py
def write_memo():
    text = input("メモの内容を入力してください: ")
    with open("memo.txt", "a", encoding="utf-8") as file:
        file.write(text + "\n")
    print("メモを保存しました!")

def read_memo():
    try:
        with open("memo.txt", "r", encoding="utf-8") as file:
            print("\n=== 保存されたメモ ===")
            print(file.read())
    except FileNotFoundError:
        print("まだメモがありません。")

while True:
    choice = input("\nメモを書く (w) / メモを読む (r) / 終了 (q): ").lower()
    if choice == "w":
        write_memo()
    elif choice == "r":
        read_memo()
    elif choice == "q":
        break
    else:
        print("無効な入力です。")

コードの流れ

このコードは メモ帳プログラム を実装したもので、以下の 3 つの機能を持っています。

  • メモの書き込み (write_memo)
    ユーザーが入力した内容をテキストファイルに保存します。

  • メモの読み込み (read_memo)
    保存されたメモを読み取り、表示します。

  • メニュー選択とループ処理 (while True)
    ユーザーが選択肢を選び、処理を繰り返し実行できるようにします。

実際に実行してみる

まず、以下のコマンドを実行して作成したコードの動作を確認します。

python test.py

実行結果

 ~/Desktop ((git)-[main])  python test.py

メモを書く (w) / メモを読む (r) / 終了 (q): w
メモの内容を入力してください: aaa
メモを保存しました!

メモを書く (w) / メモを読む (r) / 終了 (q): r

=== 保存されたメモ ===
aaa


メモを書く (w) / メモを読む (r) / 終了 (q): q

実際の画面

Screenshot 2025-02-05 at 7.34.01.png

コードの解説

メモの書き込み処理

def write_memo():
    text = input("メモの内容を入力してください: ")
    with open("memo.txt", "a", encoding="utf-8") as file:
        file.write(text + "\n")
    print("メモを保存しました!")

解説

  • ユーザーにメモの内容を入力させる (input())
    → 入力された文字列を text という変数に格納。

  • memo.txt を追記モード ("a") で開く
    "a"(append)モードを使うことで、新しいメモを既存の内容に追加できる。

  • 入力内容 (text) をファイルに書き込む
    file.write(text + "\n") で改行を加えながら保存する。

  • 保存完了のメッセージを表示

メモの読み込み処理

def read_memo():
    try:
        with open("memo.txt", "r", encoding="utf-8") as file:
            print("\n=== 保存されたメモ ===")
            print(file.read())
    except FileNotFoundError:
        print("まだメモがありません。")

解説

  • ファイル (memo.txt) を読み取りモード ("r") で開く
    with open("memo.txt", "r", encoding="utf-8") でファイルを開き、変数 file に格納。

  • メモの内容を画面に表示
    file.read() でファイルの中身をすべて読み取る。

  • ファイルが存在しない場合の処理 (except FileNotFoundError)
    memo.txt がまだ作成されていない場合、「まだメモがありません。」とメッセージを表示。

メニュー選択とループ処理

while True:
    choice = input("\nメモを書く (w) / メモを読む (r) / 終了 (q): ").lower()
    if choice == "w":
        write_memo()
    elif choice == "r":
        read_memo()
    elif choice == "q":
        break
    else:
        print("無効な入力です。")

解説

  • 無限ループ (while True) を使い、ユーザーが操作を選択できるようにする。

  • ユーザーの入力 (input()) を小文字に変換 (.lower()) し、変数 choice に格納。
    "W""R" を入力しても問題なく動作するようにする。

  • 入力値 (choice) に応じて処理を分岐。

    • "w" の場合、write_memo() を実行してメモを書く。
    • "r" の場合、read_memo() を実行してメモを表示する。
    • "q" の場合、break でループを抜け、プログラムを終了する。
    • それ以外の入力は無効として、「無効な入力です。」とメッセージを表示。

まとめ

最後までお読みいただき、ありがとうございました。Python の open() を使ったファイル操作(読み書き)を実装することで、関数の仕組みや活用方法への理解が深まりました。

今後も、このような基礎的な内容を分かりやすく整理し、丁寧にまとめていきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?