Python 파일 작업

PythonBeginner
지금 연습하기

소개

별들을 가로질러 광대한 대도시를 건설하며 인류가 승천한 유토피아적 미래에 오신 것을 환영합니다. 여러분은 멀리 떨어진 외계 행성을 공전하는 최첨단 우주 도시, 셀레스티아 (Celestia) 에 있습니다. 셀레스티아의 주요 건축가 중 한 명으로서, 여러분은 기능적이면서도 웅장한 생활 공간을 설계하기 위해 고급 시뮬레이션 소프트웨어를 사용합니다.

이 랩의 목표는 Python 의 강력한 기능을 활용하여 방대한 양의 건축 계획 및 문서를 관리하는 데 도움이 되는 일련의 도구를 개발하는 것입니다. 우주 도시의 청사진 유지 관리에 수반되는 지루한 파일 작업을 자동화하여 도시의 발전과 효율성에 기여하는 것을 목표로 합니다.

프로젝트 디렉토리 및 초기 청사진 파일 생성

이 단계에서는 계획에 대한 초기 파일을 생성하여 새 프로젝트의 기반을 설정합니다. 이것은 더 복잡한 파일 작업을 구축할 기반이 될 것입니다.

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 을 사용하여 우주 시대 환경에서 파일과 디렉토리를 탐색, 생성 및 조작하는 방법을 배웠습니다. 이러한 파일 작업을 자동화함으로써 Celestia 의 건축 노력을 위한 효율적인 파일 관리 시스템 구축을 향한 중요한 단계를 밟았습니다. Python 으로 파일 작업을 처리하는 능력은 다양한 실제 응용 프로그램으로 이어질 수 있는 귀중한 기술이며, 이 랩을 통해 얻은 경험은 이러한 능력을 강화했습니다.