python

11편 Python 기초 문법: 파일 및 디렉토리 다루기

파이썬 티쳐 2024. 11. 15. 08:52

1. 파일과 디렉토리 다루기 기초

1.1 파일과 디렉토리의 개념

  • 파일: 파일은 데이터를 저장하는 기본 단위입니다. 텍스트 파일, 이미지 파일, 실행 파일 등이 포함됩니다.
  • 디렉토리(폴더): 디렉토리는 파일을 저장하고 구조적으로 관리하기 위한 공간입니다.

1.2 os 모듈 소개

Python에서 파일과 디렉토리를 다루기 위해 os 모듈을 사용합니다. 이 모듈은 파일 시스템에서 다양한 작업을 처리할 수 있는 함수들을 제공합니다.

import os

1.3 파일 경로 처리 (os.path)

os.path는 파일 경로와 관련된 작업을 쉽게 처리할 수 있는 서브 모듈입니다.

file_path = os.path.join("folder", "example.txt")
print(file_path)  # 출력: folder/example.txt

1.4 디렉토리 생성과 삭제 (os.mkdir(), os.rmdir())

디렉토리를 생성하거나 삭제하는 방법입니다.

# 디렉토리 생성
os.mkdir("new_folder")

# 디렉토리 삭제 (비어 있을 때만 가능)
os.rmdir("new_folder")

2. 파일 및 디렉토리 작업

2.1 파일 존재 여부 확인 (os.path.exists())

파일이나 디렉토리가 존재하는지 확인할 때 os.path.exists()를 사용합니다.

if os.path.exists("example.txt"):
    print("파일이 존재합니다.")
else:
    print("파일이 존재하지 않습니다.")

2.2 파일 복사 및 이동 (shutil 모듈 사용)

shutil 모듈은 파일 및 디렉토리 복사와 이동과 같은 고급 파일 작업을 처리합니다.

import shutil

# 파일 복사
shutil.copy("example.txt", "copy_example.txt")

# 파일 이동
shutil.move("copy_example.txt", "backup/copy_example.txt")

2.3 디렉토리 내 파일 목록 가져오기 (os.listdir())

디렉토리 내에 있는 파일과 하위 디렉토리 목록을 가져오기 위해 os.listdir()을 사용합니다.

files = os.listdir("some_directory")
print(files)  # 디렉토리 내 모든 파일과 폴더 목록 출력

3. 파일 시스템을 활용한 프로그램

3.1 폴더 내 파일 정리 프로그램 작성하기 (파일 확장자에 따라 분류)

다양한 확장자를 가진 파일들을 각기 다른 디렉토리로 분류하는 프로그램을 작성할 수 있습니다.

import os
import shutil

def organize_files_by_extension(folder):
    for filename in os.listdir(folder):
        ext = filename.split(".")[-1]  # 파일 확장자 추출
        ext_folder = os.path.join(folder, ext)

        # 확장자 폴더가 없으면 생성
        if not os.path.exists(ext_folder):
            os.mkdir(ext_folder)

        # 파일을 해당 확장자 폴더로 이동
        shutil.move(os.path.join(folder, filename), os.path.join(ext_folder, filename))

# 사용 예시
organize_files_by_extension("my_folder")

위 코드는 파일의 확장자를 기준으로 폴더를 생성하고, 해당 폴더로 파일을 이동시킵니다. 예를 들어 .txt, .jpg 파일을 각각 txt, jpg 폴더에 정리할 수 있습니다.

3.2 파일 존재 여부를 확인하여 데이터 백업 프로그램 만들기

파일이 존재하는지 확인하고, 파일이 존재하면 데이터를 백업하는 프로그램을 작성할 수 있습니다.

import os
import shutil

def backup_file(file_path, backup_folder):
    # 파일 존재 여부 확인
    if os.path.exists(file_path):
        # 백업 폴더가 없으면 생성
        if not os.path.exists(backup_folder):
            os.mkdir(backup_folder)
        
        # 파일 복사
        shutil.copy(file_path, backup_folder)
        print(f"{file_path} 파일을 {backup_folder}로 백업했습니다.")
    else:
        print(f"{file_path} 파일이 존재하지 않습니다.")

# 사용 예시
backup_file("data.txt", "backup")

이 프로그램은 특정 파일이 존재할 경우 백업 디렉토리에 복사하여 데이터 유실을 방지합니다.