Python でのファイルの開閉

PythonPythonBeginner
オンラインで実践に進む

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、神秘的な門番に守られた古代の寺院への冒険に挑みます。あなたの目標は、Python でファイルを開くと閉じる技術を習得することで、寺院に秘められた秘密を明かすことです。

あなたは、神秘と何世紀にもわたる秘密に包まれた古代の Python 寺院の前に立っています。知恵深く謎めいた態度で知られる門番が、Python でファイルを開くと閉じる技術を習得することであなたの価値を証明するように挑戦します。そのときのみ、聖なる寺院の中で知識の扉があなたのために開かれます。

寺院に入る

このステップでは、寺院の壁の中にあるファイルを開いて読み取るための Python スクリプトを作成することで、あなたの勇気と決意を示します。

  1. ターミナルで、/home/labex/project ディレクトリに移動します。
  2. open_file.py という名前の Python スクリプトファイルを開きます。
  3. open_file.py ファイルに次のコードを書きます:
## open_file.py
file_path = '/home/labex/project/sacred_scroll.txt'

with open(file_path, 'r') as file:
    content = file.read()
    print(content)

スクリプトを実行します:

python open_file.py

端末には以下の情報が表示されるはずです:

The ancient prophecy foretells the chosen one who shall bring balance to the realms.

秘密を明かす

このステップでは、寺院の中の知恵を保存するために、Python スクリプトを作成してファイルに書き込み、そして閉じることで、新たに身につけた知識を披露します。

  1. 同じディレクトリにある write_file.py という名前の Python スクリプトファイルを開きます。
  2. write_file.py ファイルに次のコードを書きます:
## write_file.py
file_path = '/home/labex/project/ancient_wisdom.txt'

with open(file_path, 'w') as file:
    wisdom = "The path to enlightenment begins with Python."
    file.write(wisdom)
    print("Ancient wisdom has been inscribed.")
    ## The file is automatically closed at the end of the with statement block.

スクリプトを実行します:

python write_file.py

端末には以下の情報が表示されるはずです:

Ancient wisdom has been inscribed.

同時に、ancient_wisdom.txt という名前のファイルが見え、その内容は:The path to enlightenment begins with Python. となっています。

寺院の門を閉じる

このステップでは、寺院の中のファイルを丁寧に閉じることで、古代の伝統に対する敬意を示します。

write_file.py スクリプトの末尾で以下のコードを更新します:

## write_file.py
file_path = '/home/labex/project/ancient_wisdom.txt'

file = open(file_path, 'w')
wisdom = "The path to enlightenment begins with Python."
file.write(wisdom)
print("Ancient wisdom has been inscribed.")
file.close()
## After opening a file with the open() function, the close() method should always be called to close the file in order to ensure that the resources are released correctly.

スクリプトを実行します:

python write_file.py

端末には以下の情報が表示されるはずです:

Ancient wisdom has been inscribed.

まとめ

この実験では、Python のファイル操作の世界に足を踏み入れました。ファイルの開き、読み取り、書き込み、閉じる技術を習得することで、Python の古代の知恵を明かす第一歩を踏み出しました。この知識を大切にし、啓蒙への旅を導く手がかりとしてください。