Python/Python 심화

Python 파일 입출력과 pathlib

임베디드 친구 2025. 7. 26. 17:55
728x90
반응형

Python 파일 입출력과 pathlib

Python은 다양한 파일 입출력(File I/O) 기능을 제공하며, 그중 pathlib 모듈은 파일 및 디렉토리 작업을 더욱 직관적이고 강력하게 만들어줍니다. 이 글에서는 기본 파일 입출력부터 pathlib을 사용한 파일 작업까지 자세히 다뤄보겠습니다.


1. Python 파일 입출력 기본

1.1 파일 열기와 닫기

Python에서 파일을 열고 작업한 후에는 반드시 파일을 닫아야 합니다. 이를 위해 open() 함수와 close() 메서드를 사용합니다.

# 파일 쓰기
file = open('example.txt', 'w')
file.write('Hello, Python!')
file.close()

# 파일 읽기
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

1.2 with 구문 사용

파일 작업에서 흔히 발생하는 문제는 파일을 닫는 것을 잊는 경우입니다. 이를 방지하기 위해 Python에서는 with 구문을 제공합니다. with 구문을 사용하면 작업이 끝난 후 파일이 자동으로 닫힙니다.

# 파일 쓰기
with open('example.txt', 'w') as file:
    file.write('Hello, Python with with!')

# 파일 읽기
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

2. pathlib: 현대적인 파일 및 디렉토리 작업

Python 3.4부터 도입된 pathlib 모듈은 파일 및 디렉토리 작업을 객체 지향 방식으로 처리할 수 있게 해줍니다. 이제 pathlib을 사용한 파일 작업을 살펴보겠습니다.

2.1 Path 객체 생성

pathlib의 핵심 클래스는 Path입니다. 파일 경로나 디렉토리를 표현하기 위해 Path 객체를 생성할 수 있습니다.

from pathlib import Path

# 현재 디렉토리
current_dir = Path('.')
print(current_dir.resolve())

# 특정 경로 생성
file_path = Path('example.txt')
print(file_path)

2.2 파일 쓰기

Path 객체를 사용하면 파일을 쉽게 생성하고 데이터를 쓸 수 있습니다.

from pathlib import Path

file_path = Path('example_pathlib.txt')

# 파일 쓰기
file_path.write_text('Hello, pathlib!')
print(f'File written: {file_path}')

2.3 파일 읽기

파일 내용을 읽는 것도 매우 간단합니다.

from pathlib import Path

file_path = Path('example_pathlib.txt')

# 파일 읽기
content = file_path.read_text()
print(f'File content: {content}')

2.4 파일 존재 여부 확인

파일이 존재하는지 확인할 때는 Path.exists()를 사용합니다.

from pathlib import Path

file_path = Path('example_pathlib.txt')

if file_path.exists():
    print(f'{file_path} exists.')
else:
    print(f'{file_path} does not exist.')

2.5 디렉토리 작업

Path 객체는 디렉토리 생성 및 삭제와 같은 작업도 지원합니다.

from pathlib import Path

# 디렉토리 생성
new_dir = Path('new_directory')
new_dir.mkdir(exist_ok=True)
print(f'Directory created: {new_dir}')

# 디렉토리 삭제
if new_dir.exists():
    new_dir.rmdir()
    print(f'Directory removed: {new_dir}')

3. 파일 및 디렉토리 탐색

3.1 디렉토리 내 파일 나열

Path 객체의 iterdir() 메서드를 사용하면 디렉토리의 파일과 서브디렉토리를 나열할 수 있습니다.

from pathlib import Path

current_dir = Path('.')

# 디렉토리 내 파일 나열
for item in current_dir.iterdir():
    print(item)

3.2 파일 필터링

특정 조건에 맞는 파일만 필터링할 수 있습니다. 예를 들어, .txt 확장자를 가진 파일만 나열하려면 다음과 같이 작성합니다.

from pathlib import Path

current_dir = Path('.')

# .txt 파일 필터링
for txt_file in current_dir.glob('*.txt'):
    print(txt_file)

3.3 재귀적으로 파일 탐색

rglob() 메서드를 사용하면 서브디렉토리를 포함한 모든 파일을 재귀적으로 탐색할 수 있습니다.

from pathlib import Path

current_dir = Path('.')

# 모든 .txt 파일 탐색
for txt_file in current_dir.rglob('*.txt'):
    print(txt_file)

4. 실제 활용 예제

4.1 로그 파일 관리

여러 로그 파일을 관리하고 싶을 때 pathlib을 활용하면 유용합니다.

from pathlib import Path

log_dir = Path('logs')
log_dir.mkdir(exist_ok=True)

# 로그 파일 생성
for i in range(5):
    log_file = log_dir / f'log_{i}.txt'
    log_file.write_text(f'This is log file {i}')

# 생성된 로그 파일 출력
for log_file in log_dir.iterdir():
    print(log_file.read_text())

4.2 대용량 파일 읽기

대용량 파일은 메모리 문제를 방지하기 위해 한 줄씩 읽어야 합니다.

from pathlib import Path

large_file = Path('large_file.txt')
large_file.write_text('\n'.join(f'Line {i}' for i in range(1000)))

# 한 줄씩 읽기
with large_file.open('r') as file:
    for line in file:
        print(line.strip())

5. 요약

pathlib은 Python에서 파일과 디렉토리 작업을 쉽고 직관적으로 만들어주는 강력한 모듈입니다. 이 글에서는 기본 파일 입출력부터 pathlib의 다양한 기능을 살펴보았습니다. 다음 프로젝트에서 파일 및 디렉토리 작업이 필요하다면 pathlib을 적극적으로 활용해 보세요!

728x90
반응형