0Pricing
AI Agents · 강의

디렉터리 탐색 및 파일 찾기

os.walk(), glob 패턴을 사용하고 유형이나 날짜로 파일을 필터링합니다.

디렉터리 탐색 및 파일 찾기은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

에이전트에 디렉터리 순회가 필요한 이유

에이전트는 특정 조건에 맞는 파일을 찾아야 하는 경우가 많습니다. 예를 들어 코드베이스의 모든 Python 파일, 데이터 디렉터리의 모든 CSV 파일, 최근 로그를 찾을 수 있습니다. Python은 os.walk(), Path.iterdir(), Path.rglob()라는 세 가지 주요 도구를 제공합니다. 얼마나 깊이 검색해야 하는지에 따라 각 도구의 장점이 다릅니다.

import os
from pathlib import Path

# Count all files in a directory tree
root = Path('/tmp/agent_workspace')
file_count = sum(1 for f in root.rglob('*') if f.is_file())
print(f'Found {file_count} files under {root}')

os.walk() — 재귀적 디렉터리 순회

os.walk(root)는 디렉터리 트리의 모든 디렉터리에 대해 (dirpath, dirnames, filenames) 튜플을 생성합니다. 재귀적 순회를 위한 Python의 전통적인 방식이며, 어떤 하위 디렉터리로 내려갈지 세밀하게 제어할 수 있습니다.

import os
import tempfile

# --- demo setup: build a small project tree so the walk has something to show ---
root = tempfile.mkdtemp(prefix='project_')
os.makedirs(os.path.join(root, 'src'), exist_ok=True)
os.makedirs(os.path.join(root, '.git'), exist_ok=True)
with open(os.path.join(root, 'README.md'), 'w') as f:
    f.write('demo')
with open(os.path.join(root, 'src', 'main.py'), 'w') as f:
    f.write('print(1)')

for dirpath, dirnames, filenames in os.walk(root):
    # Skip hidden directories (like .git)
    dirnames[:] = [d for d in dirnames if not d.startswith('.')]

    print(f'In directory: {dirpath}')
    print(f'  Subdirs: {dirnames}')
    print(f'  Files: {filenames}')

    for filename in filenames:
        full_path = os.path.join(dirpath, filename)
        print(f'  File: {full_path}')

Path.iterdir() — 한 수준 목록

Path.iterdir()는 디렉터리의 바로 아래 항목을 나열하며, 하위 디렉터리로 재귀하지 않습니다. 디렉터리의 직접적인 하위 항목만 필요하고 더 깊이 내려가는 것을 피하고 싶을 때 사용하십시오.

from pathlib import Path

data_dir = Path('data')
data_dir.mkdir(exist_ok=True)
(data_dir / 'a.csv').write_text('x')
(data_dir / 'sub').mkdir(exist_ok=True)

for item in data_dir.iterdir():
    if item.is_file():
        print(f'FILE: {item.name} ({item.stat().st_size} bytes)')
    elif item.is_dir():
        print(f'DIR:  {item.name}/')

csv_files = [f for f in data_dir.iterdir()
             if f.is_file() and f.suffix == '.csv']
print(f'Found {len(csv_files)} CSV files')

Path.rglob() — 재귀적 glob

Path.rglob(pattern)은 glob 패턴과 일치하는 모든 파일을 재귀적으로 찾습니다. 디렉터리 트리의 어느 위치에 있든 특정 유형의 파일을 모두 찾을 때 가장 간결한 방법입니다. glob에서 **는 “디렉터리가 몇 개든”을 의미합니다.

from pathlib import Path

project = Path('/tmp/my_project')

# Find all Python files recursively
python_files = list(project.rglob('*.py'))
print(f'Found {len(python_files)} Python files:')
for f in python_files:
    print(f'  {f.relative_to(project)}')

# Find all JSON files
json_files = list(project.rglob('*.json'))

# Find files matching a name pattern
test_files = list(project.rglob('test_*.py'))
print(f'Found {len(test_files)} test files')

glob.glob() — 패턴 일치

glob.glob(pattern, recursive=True)는 전통적인 glob 인터페이스입니다. recursive=True를 사용하면 ** 와일드카드가 모든 하위 디렉터리 경로와 일치합니다. 이 함수는 문자열을 반환하는 반면, pathlib.rglob는 Path 객체를 반환합니다.

import glob

# Find all CSV files recursively
csv_files = glob.glob('data/**/*.csv', recursive=True)
print(f'Found {len(csv_files)} CSV files')
for f in csv_files:
    print(f'  {f}')

# Find all log files in a specific directory (non-recursive)
logs = glob.glob('/var/log/*.log')

# Find files matching multiple criteria
import fnmatch
all_files = glob.glob('/tmp/**/*', recursive=True)
config_files = [
    f for f in all_files
    if fnmatch.fnmatch(f, '*.yaml') or fnmatch.fnmatch(f, '*.yml')
]
print(f'Found {len(config_files)} YAML config files')

파일 확장자로 필터링하기

디렉터리를 순회할 때는 Path.suffix(점도 포함합니다. 예: '.py')를 사용하거나 허용되는 확장자 집합과 비교하여 파일을 확장자로 필터링하십시오. 여러 확장자를 필터링할 때는 glob 패턴보다 빠르고 정확합니다.

from pathlib import Path

directory = Path('/tmp/mixed_files')

ALLOWED_EXTENSIONS = {'.py', '.js', '.ts', '.json', '.yaml'}

# Filter by allowed extensions
code_files = [
    f for f in directory.rglob('*')
    if f.is_file() and f.suffix.lower() in ALLOWED_EXTENSIONS
]

print(f'Found {len(code_files)} code/config files')

# Group files by extension
from collections import defaultdict
by_ext = defaultdict(list)
for f in directory.rglob('*'):
    if f.is_file():
        by_ext[f.suffix].append(f)

for ext, files in sorted(by_ext.items()):
    print(f'{ext}: {len(files)} files')

파일 크기로 필터링하기

에이전트는 때때로 특정 크기 기준보다 크거나 작은 파일을 찾아야 합니다. 너무 작은 빈 파일을 건너뛰거나 메모리를 과도하게 사용하는 대용량 파일의 처리를 피할 수 있습니다. 파일 크기를 바이트 단위로 가져오려면 Path.stat().st_size를 사용하십시오.

from pathlib import Path

data_dir = Path('/tmp/data')

MIN_SIZE = 1024        # 1 KB — skip empty/tiny files
MAX_SIZE = 50_000_000  # 50 MB — skip very large files

processable = []
skipped_small = []
skipped_large = []

for f in data_dir.rglob('*.json'):
    if not f.is_file():
        continue
    size = f.stat().st_size
    if size < MIN_SIZE:
        skipped_small.append(f.name)
    elif size > MAX_SIZE:
        skipped_large.append(f.name)
    else:
        processable.append(f)

print(f'Processable: {len(processable)}')
print(f'Too small: {len(skipped_small)}')
print(f'Too large: {len(skipped_large)}')

수정 시간으로 필터링하기

증분 처리 흐름의 에이전트는 마지막 실행 이후 변경된 파일만 처리하면 됩니다. stat().st_mtime(유닉스 타임스탬프로 표현된 수정 시간)를 사용하여 최근에 수정된 파일을 찾으십시오.

from pathlib import Path
import time
import datetime

data_dir = Path('/tmp/data')

# Files modified in the last 24 hours
cutoff = time.time() - (24 * 60 * 60)

recent_files = [
    f for f in data_dir.rglob('*.log')
    if f.is_file() and f.stat().st_mtime > cutoff
]

print(f'Modified in last 24h: {len(recent_files)} files')

# Sort by modification time (newest first)
recent_files.sort(key=lambda f: f.stat().st_mtime, reverse=True)

for f in recent_files[:5]:  # top 5 most recent
    mtime = datetime.datetime.fromtimestamp(f.stat().st_mtime)
    print(f'  {f.name}: {mtime.strftime("%Y-%m-%d %H:%M:%S")}')

숨김 파일 및 시스템 디렉터리 건너뛰기

코드 저장소나 사용자 디렉터리를 순회할 때는 숨김 파일(.으로 시작하는 파일)과 .git, __pycache__, node_modules, .venv 같은 시스템 디렉터리를 건너뛰십시오. 이러한 위치에는 대부분의 에이전트와 관련 없는 파일이 수천 개씩 들어 있습니다.

from pathlib import Path

SKIP_DIRS = {'.git', '__pycache__', 'node_modules', '.venv',
             '.env', 'dist', 'build', '.mypy_cache'}

def iter_source_files(root, extensions):
    root = Path(root)
    for path in root.rglob('*'):
        # Skip if any parent is in SKIP_DIRS
        if any(part in SKIP_DIRS for part in path.parts):
            continue
        # Skip hidden files
        if path.name.startswith('.'):
            continue
        if path.is_file() and path.suffix in extensions:
            yield path

python_files = list(iter_source_files('/tmp/project', {'.py'}))
print(f'Found {len(python_files)} Python source files')

파일 목록 만들기

파일 목록은 디렉터리 트리를 구조적으로 요약한 것입니다. 처리하기 전에 작업을 계획해야 하는 에이전트에 유용합니다. 이름, 경로, 크기, 확장자, 수정 시간을 수집하여 JSON으로 직렬화할 수 있는 딕셔너리 목록에 저장하십시오.

from pathlib import Path
import datetime
import json

def build_inventory(root_dir, pattern='**/*'):
    root = Path(root_dir)
    inventory = []

    for f in root.glob(pattern):
        if not f.is_file():
            continue
        stat = f.stat()
        inventory.append({
            'name': f.name,
            'path': str(f.relative_to(root)),
            'extension': f.suffix,
            'size_bytes': stat.st_size,
            'modified': datetime.datetime.fromtimestamp(
                stat.st_mtime
            ).isoformat()
        })

    return sorted(inventory, key=lambda x: x['path'])

inventory = build_inventory('/tmp/data')
with open('file_inventory.json', 'w') as out:
    json.dump(inventory, out, indent=2)
print(f'Inventoried {len(inventory)} files')

변경 사항을 감지하도록 디렉터리 감시하기

일부 에이전트는 디렉터리에 새 파일이 나타나면 이에 반응해야 합니다. watchdog 같은 완전한 파일 감시 라이브러리가 운영 환경에는 가장 적합하지만, 간단한 방법은 주기적으로 디렉터리를 검색하고 알려진 파일 집합과 비교하는 것입니다.

from pathlib import Path
import time

def watch_for_new_files(watch_dir, extension='.json', interval=5):
    watch_dir = Path(watch_dir)
    known_files = set(watch_dir.glob(f'*{extension}'))
    print(f'Watching {watch_dir} for new {extension} files...')

    while True:
        time.sleep(interval)
        current_files = set(watch_dir.glob(f'*{extension}'))
        new_files = current_files - known_files

        for f in new_files:
            print(f'New file detected: {f.name}')
            process_new_file(f)  # handle the new file

        known_files = current_files

def process_new_file(file_path):
    print(f'Processing: {file_path}')

# --- demo (one polling cycle, without the infinite while True loop) ---
import tempfile
demo_dir = Path(tempfile.mkdtemp())
known_files = set(demo_dir.glob('*.json'))
print(f'Watching {demo_dir} for new .json files...')

(demo_dir / 'result_a.json').write_text('{}', encoding='utf-8')
(demo_dir / 'result_b.json').write_text('{}', encoding='utf-8')

current_files = set(demo_dir.glob('*.json'))
new_files = current_files - known_files
for f in sorted(new_files, key=lambda p: p.name):
    print(f'New file detected: {f.name}')
    process_new_file(f)

빠른 확인: rglob과 iterdir 비교

디렉터리 순회 방법에 대한 이해도를 확인합니다.

디렉터리 순회 복습

이제 에이전트에 필요한 모든 파일을 찾을 수 있습니다.

  • os.walk() — 재귀적 순회를 완전히 제어하며, 하위 디렉터리를 제거하려면 dirnames를 제자리에서 수정합니다
  • Path.iterdir() — 바로 아래 항목을 한 수준으로 나열합니다
  • Path.rglob('*.ext') — 패턴을 사용한 가장 깔끔한 재귀 검색입니다
  • glob.glob('**/*.ext', recursive=True) — 문자열을 반환하는 전통적인 대안입니다
  • 확장자는 .suffix, 크기는 .stat().st_size, 수정 시간은 .stat().st_mtime으로 필터링합니다
  • 항상 숨김 파일과 .git, node_modules 같은 시스템 디렉터리를 건너뜁니다

자주 묻는 질문

“디렉터리 탐색 및 파일 찾기” 강의는 무료인가요?

네 — “디렉터리 탐색 및 파일 찾기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

“디렉터리 탐색 및 파일 찾기”에서 뭘 배우나요?

os.walk(), glob 패턴을 사용하고 유형이나 날짜로 파일을 필터링합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“디렉터리 탐색 및 파일 찾기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 에이전트 환경에서 파일 읽기 및 쓰기
  2. 디렉터리 탐색 및 파일 찾기
  3. 파일 형식 처리: CSV, JSON, TXT
  4. 오류 처리를 적용한 안전한 파일 작업
← AI Agents(으)로 돌아가기