すべての青写真ファイルを一覧表示して内容を読み取る
このステップでは、ディレクトリ内のすべての青写真ファイルを一覧表示し、特定のファイルの内容を読み取るスクリプトを開発します。
今のところ、ディレクトリ内に複数の青写真ファイルがあると仮定します。/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.