Python ファイル操作

PythonPythonBeginner
今すぐ練習

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

はじめに

空想的な未来へようこそ。人類は星の果てに広大な大都市を建設するために進化しました。あなたは遠い太陽系外惑星を周回する最先端の宇宙都市セレスティアにいます。セレスティアの一流の建築家の一人として、あなたは高度なシミュレーションソフトウェアを使って、機能的で壮大な住居空間をデザインします。

この実験のあなたの目標は、膨大な建築計画と文書を管理するのに役立つ一連のツールを開発するために、Python の力を利用することです。あなたは宇宙都市の青写真の維持に伴う退屈なファイル操作を自動化することを目指し、都市の進歩と効率に貢献します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python/FileHandlingGroup -.-> python/file_operations("File Operations") subgraph Lab Skills python/file_operations -.-> lab-271551{{"Python ファイル操作"}} end

初期の青写真ファイルの作成

このステップでは、計画の初期ファイルを作成することで、新しいプロジェクトの基礎をセットアップします。これが、より複雑なファイル操作を構築する基盤になります。

Python を使ってこのファイルにいくつかの基本情報を書き込みましょう。~/projectにあるwrite_plan.pyファイルを開きます:

## write_plan.py
plan_content = """Celestia Oxygen Gardens Blueprint
Architect: [Your Name]
Last Updated: [Today's Date]
This space garden is designed to provide ample oxygen supply and recreational space to Celestia residents.
"""

with open('/home/labex/project/oxygen_gardens.txt', 'w') as file:
    file.write(plan_content)

~/projectという現在の作業ディレクトリからこのスクリプトを実行します:

python write_plan.py

catコマンドでファイルの内容を確認します:

cat /home/labex/project/oxygen_gardens.txt

端末に書き込んだ内容が表示されるはずです:

Celestia Oxygen Gardens Blueprint
Architect: [Your Name]
Last Updated: [Today's Date]
This space garden is designed to provide ample oxygen supply and recreational space to Celestia residents.

すべての青写真ファイルを一覧表示して内容を読み取る

このステップでは、ディレクトリ内のすべての青写真ファイルを一覧表示し、特定のファイルの内容を読み取るスクリプトを開発します。

今のところ、ディレクトリ内に複数の青写真ファイルがあると仮定します。/home/labex/project/ディレクトリに存在するすべての.txtのテキストファイルを一覧表示するlist_blueprints.pyスクリプトを開きます。

## list_blueprints.py
import os

## Define the blueprints directory path
blueprints_dir = '/home/labex/project/'

## List all files in the directory
files = os.listdir(blueprints_dir)

## Filter out non-txt files and print the remaining files
print("Blueprint Files:")
for file in files:
    if file.endswith('.txt'):
        print(file)

## Assume 'oxygen_gardens.txt' is the file we want to read
file_to_read = 'oxygen_gardens.txt'
with open(os.path.join(blueprints_dir, file_to_read), 'r') as file:
    print(f"\nContents of {file_to_read}:")
    print(file.read())

プロジェクトディレクトリの端末からスクリプトを実行します:

python list_blueprints.py

出力は、すべての青写真ファイルの一覧と、oxygen_gardens.txtの内容が続きます:

Blueprint Files:
oxygen_gardens.txt

Contents of oxygen_gardens.txt:
Celestia Oxygen Gardens Blueprint
Architect: [Your Name]
Last Updated: [Today's Date]
This space garden is designed to provide ample oxygen supply and recreational space to Celestia residents.

まとめ

この実験では、宇宙時代の設定で Python を使ってファイルやディレクトリをナビゲートし、作成し、操作する方法を学びました。これらのファイル操作を自動化することで、セレスティアの建築活動に対する効率的なファイル管理システムを構築するための重要なステップを踏み出しました。Python を使ってファイル操作を処理する能力は、さまざまな実世界のアプリケーションに応用できる貴重なスキルであり、この実験を通じてその能力を強化しました。