PHpullh
학습 라이브러리/Python/비동기 파일 I/O

PYTHON · 비동기

비동기 파일 I/O

파일 I/O를 비동기로 처리하여 이벤트 루프를 블로킹하지 않는 방법입니다.

비동기중급aiofilesfile IO비동기run_in_executor

핵심 설명

파일 I/O를 비동기로 처리하여 이벤트 루프를 블로킹하지 않는 방법입니다.

Python code

import asyncio

# run_in_executor로 동기 I/O를 비동기로
async def read_file_async(path: str) -> str:
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        None,  # 기본 ThreadPoolExecutor
        lambda: open(path).read() if __import__('os').path.exists(path)
                else f"파일 없음: {path}"
    )

# 여러 파일 동시 읽기
async def read_many(paths: list[str]):
    tasks = [read_file_async(p) for p in paths]
    return await asyncio.gather(*tasks)

# aiofiles 패턴 시뮬레이션
class AsyncFile:
    def __init__(self, content=""):
        self.content = content

    async def __aenter__(self):
        await asyncio.sleep(0.01)  # I/O 시뮬레이션
        return self

    async def __aexit__(self, *args):
        pass

    async def read(self):
        await asyncio.sleep(0.01)
        return self.content

    async def write(self, data):
        await asyncio.sleep(0.01)
        self.content += data

async def main():
    # 동시 파일 처리
    async with AsyncFile("Hello, World!") as f:
        content = await f.read()
        print(f"내용: {content}")

    print("비동기 파일 I/O 완료")

asyncio.run(main())

학습 팁

실제 프로젝트에서는 pip install aiofiles를 사용하세요. async with aiofiles.open() as f:로 간편하게 비동기 파일 I/O를 수행합니다.

주의할 점

일반 open()은 동기적으로 블로킹합니다. 비동기 환경에서 대용량 파일을 다룰 때는 반드시 비동기 I/O를 사용하세요.

자주 묻는 질문

비동기 파일 I/O란 무엇인가요?

파일 I/O를 비동기로 처리하여 이벤트 루프를 블로킹하지 않는 방법입니다.

비동기 파일 I/O 학습 시 주의할 점은 무엇인가요?

일반 open() 은 동기적으로 블로킹합니다. 비동기 환경에서 대용량 파일을 다룰 때는 반드시 비동기 I/O를 사용하세요.

Continue Learning

Python 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.