0Pricing
AI Agents · 강의

에이전트 환경에서 파일 읽기 및 쓰기

에이전트 도구에서 open(), pathlib.Path를 사용해 CSV/JSON/TXT 파일을 읽습니다.

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

에이전트에서 파일 입출력이 중요한 이유

에이전트는 구성 정보를 읽고, 중간 결과를 저장하며, 출력 보고서를 작성해야 하는 경우가 많습니다. Python에서는 파일을 다루는 두 가지 주요 방법으로 기본 제공 open() 함수와 최신 경로 처리 모듈을 제공합니다. 두 방법 모두 반드시 알아야 합니다.

모든 파일 작업은 컨텍스트 관리자(with 문)를 사용하여 오류가 발생하더라도 파일이 닫히도록 해야 합니다.

with open('config.txt', 'w', encoding='utf-8') as f:
    f.write('model=gpt-4o-mini\nmax_steps=20\n')

with open('config.txt', 'r', encoding='utf-8') as f:
    content = f.read()

from pathlib import Path
content = Path('config.txt').read_text(encoding='utf-8')

print(content)

파일 열기로 파일 읽기

open() 함수에는 파일 이름과 모드를 전달합니다. 텍스트를 읽으려면 'r' 모드를 사용하세요. .read()로 파일 전체를 한 번에 읽거나, .readline()으로 한 줄씩 읽거나, .readlines()로 모든 줄을 목록에 담을 수 있습니다.

플랫폼별 인코딩 문제를 피하려면 항상 encoding='utf-8'을 지정하세요.

with open('report.txt', 'w', encoding='utf-8') as f:
    f.write('Quarterly agent report body text.')
with open('large_log.txt', 'w', encoding='utf-8') as f:
    f.write('INFO: started\nERROR: timeout\nINFO: done\n')
with open('tasks.txt', 'w', encoding='utf-8') as f:
    f.write('task one\ntask two\n')

with open('report.txt', 'r', encoding='utf-8') as f:
    full_text = f.read()
    print(f'Read {len(full_text)} characters')

with open('large_log.txt', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.rstrip('\n')
        if 'ERROR' in line:
            print('Found error:', line)

with open('tasks.txt', 'r', encoding='utf-8') as f:
    tasks = f.readlines()
    tasks = [t.strip() for t in tasks]
print('Tasks:', tasks)

파일 열기로 파일 쓰기

쓰기에는 'w' 모드를 사용하세요. 이 모드는 파일을 생성하거나 덮어씁니다. 'a'는 내용을 추가하고, 'x'는 배타적으로 파일을 생성하므로 파일이 이미 있으면 실패합니다. 'w' 모드는 먼저 파일을 잘라내므로 기존 데이터가 있을 때 주의하세요.

# Write a new file (or overwrite)
results = ['Task 1 complete', 'Task 2 complete', 'Task 3 failed']

with open('results.txt', 'w', encoding='utf-8') as f:
    for result in results:
        f.write(result + '\n')

# Append to existing file (add without overwriting)
with open('agent_log.txt', 'a', encoding='utf-8') as f:
    f.write('2026-05-29 14:30: Agent completed batch\n')

# Create exclusively — error if file already exists
try:
    with open('unique_report.txt', 'x', encoding='utf-8') as f:
        f.write('This file is new')
except FileExistsError:
    print('File already exists, skipping')

# --- demo ---
print('results.txt contents:')
with open('results.txt', encoding='utf-8') as f:
    print(f.read())

# Try the exclusive create again now that the file exists
try:
    with open('unique_report.txt', 'x', encoding='utf-8') as f:
        f.write('This file is new')
except FileExistsError:
    print('File already exists, skipping')

pathlib.Path — 현대적인 파일 작업

pathlib.Path는 파일 경로를 객체 지향적으로 다루는 방법을 제공합니다. os.path보다 읽기 쉽고 플랫폼마다 다른 경로 구분자를 자동으로 처리합니다. 간단한 읽기 및 쓰기 작업에는 read_text()와 write_text()를 사용하는 방식이 가장 깔끔합니다.

from pathlib import Path

base = Path('agent_workspace')
base.mkdir(exist_ok=True)
config_file = base / 'config.json'
config_file.write_text('{"model": "gpt-4o-mini"}', encoding='utf-8')

if config_file.exists():
    content = config_file.read_text(encoding='utf-8')
    print('Config:', content)

output = base / 'output' / 'report.txt'
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text('Agent report\nLine 2', encoding='utf-8')

Path('image.png').write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(100)))
binary_data = Path('image.png').read_bytes()
print(f'File size: {len(binary_data)} bytes')

JSON 파일 읽기 및 쓰기

에이전트는 구조화된 데이터를 JSON 파일로 자주 주고받습니다. JSON 파일을 파싱하려면 json.load()를 사용하고, 파일에 쓰려면 json.dump()를 사용합니다. 사람이 읽기 쉬운 출력을 위해 항상 indent=2를 사용하고, 유니코드 문자를 보존하려면 ensure_ascii=False를 사용합니다.

import json
from pathlib import Path

config_path = Path('agent_config.json')
config_path.write_text(json.dumps({'max_retries': 5, 'model': 'gpt-4o-mini'}), encoding='utf-8')

with open(config_path, 'r', encoding='utf-8') as f:
    config = json.load(f)

print('Max retries:', config.get('max_retries', 3))
print('Model:', config.get('model', 'gpt-4o-mini'))

results = {
    'run_id': 'run-001',
    'status': 'completed',
    'items_processed': 142,
    'errors': []
}

with open('results.json', 'w', encoding='utf-8') as f:
    json.dump(results, f, indent=2, ensure_ascii=False)

print('Results written to results.json')

컨텍스트 관리자 — 올바른 방법

with 문(컨텍스트 관리자)은 블록이 끝날 때 파일이 닫히도록 보장합니다. 읽는 도중 예외가 발생하더라도 마찬가지입니다. 이를 사용하지 않으면 파일이 열린 채로 남아 파일 디스크립터가 누수될 수 있으며, 파일 핸들 수에 제한이 있는 시스템에서는 충돌이 발생할 수 있습니다.

with open('data.txt', 'w', encoding='utf-8') as f:
    f.write('sample content')

f = open('data.txt', 'r')
try:
    content = f.read()
finally:
    f.close()

with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()

with open('input.txt', 'w', encoding='utf-8') as f:
    f.write('hello\nworld\n')

with open('input.txt', 'r') as infile, \
     open('output.txt', 'w') as outfile:
    for line in infile:
        processed = line.upper()
        outfile.write(processed)

print('Done:', content)

바이너리 파일 다루기

바이너리 파일(이미지, PDF, 오디오)을 읽을 때는 모드 'rb'를 사용하고, 쓸 때는 'wb'를 사용합니다. 바이너리 콘텐츠를 텍스트로 decode하려고 하지 마십시오. pathlib에서는 read_bytes()/write_bytes()를 사용하고, open()에서는 바이너리 모드를 사용하십시오.

from pathlib import Path
import base64

image_path = Path('screenshot.png')
image_path.write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(50)))

image_bytes = image_path.read_bytes()
print(f'Image size: {len(image_bytes)} bytes')

image_b64 = base64.b64encode(image_bytes).decode('utf-8')
print(f'Base64 length: {len(image_b64)}')

response_bytes = b'...binary content from API...'
output_path = Path('output') / 'generated_image.png'
output_path.parent.mkdir(exist_ok=True)
output_path.write_bytes(response_bytes)
print('Wrote', output_path)

인코딩 및 줄바꿈 문제 처리

시스템마다 사용하는 줄바꿈 문자가 다릅니다(Linux/macOS에서는 \n, Windows에서는 \r\n). 항상 encoding='utf-8'를 지정하고, newline=None(기본값)을 사용하여 Python이 줄바꿈을 처리하도록 하십시오. BOM(바이트 순서 표시)이 있는 파일에는 encoding='utf-8-sig'를 사용하십시오.

with open('data.txt', 'w', encoding='utf-8') as f:
    f.write('hello world')
with open('windows_export.csv', 'wb') as f:
    f.write('name,email\n'.encode('utf-8'))
with open('unknown_encoding.txt', 'wb') as f:
    f.write('cafe resume'.encode('latin-1'))

with open('data.txt', 'r', encoding='utf-8') as f:
    text = f.read()

with open('windows_export.csv', 'r', encoding='utf-8-sig') as f:
    content = f.read()

try:
    with open('unknown_encoding.txt', 'r', encoding='utf-8') as f:
        text = f.read()
except UnicodeDecodeError:
    with open('unknown_encoding.txt', 'r',
               encoding='utf-8', errors='replace') as f:
        text = f.read()
    print('Warning: file had encoding errors (replaced with ?)')

print('All reads completed. csv content:', repr(content))

효율적인 한 줄씩 처리

대용량 파일(로그 파일, 데이터 세트)을 다룰 때는 .read()로 모든 내용을 메모리에 불러오지 마십시오. 파일 객체를 직접 순회하면 Python이 한 번에 한 줄씩 읽으므로 파일 크기와 관계없이 메모리 사용량을 일정하게 유지할 수 있습니다.

from pathlib import Path

def process_large_log(log_path):
    error_count = 0
    processed = 0

    with open(log_path, 'r', encoding='utf-8') as f:
        for line in f:  # reads one line at a time
            line = line.strip()
            if not line:
                continue

            processed += 1
            if '[ERROR]' in line:
                error_count += 1
                # Process error immediately without storing all lines
                handle_error(line)

    print(f'Processed {processed} lines, {error_count} errors')

def handle_error(line):
    print(f'Error found: {line[:80]}')

# --- demo ---
with open('demo_agent.log', 'w', encoding='utf-8') as f:
    f.write('[INFO] agent started\n')
    f.write('[ERROR] timeout calling tool search_web\n')
    f.write('[INFO] retrying\n')
    f.write('[ERROR] tool search_web failed again\n')

process_large_log('demo_agent.log')

디렉터리 만들기 및 관리

파일을 쓰기 전에 상위 디렉터리가 존재하는지 확인하십시오. Path.mkdir(parents=True, exist_ok=True)를 사용하면 중첩된 디렉터리를 만들 수 있으며, 이미 존재하더라도 오류가 발생하지 않습니다. 출력 파일을 생성하는 모든 에이전트의 시작 부분에서 흔히 수행하는 설정 단계입니다.

from pathlib import Path
import datetime

# Create output directory structure
today = datetime.date.today().isoformat()  # '2026-05-29'
output_dir = Path('agent_output') / today / 'reports'
output_dir.mkdir(parents=True, exist_ok=True)

print(f'Output directory: {output_dir}')

# Now write files safely
for i in range(3):
    report_path = output_dir / f'report_{i:02d}.json'
    report_path.write_text(
        '{"status": "ok"}',
        encoding='utf-8'
    )

# List all created files
for f in output_dir.iterdir():
    print(f'  {f.name}: {f.stat().st_size} bytes')

에이전트를 위한 파일 경로 모범 사례

에이전트는 절대 경로나 잘 정의된 기준 디렉터리에 상대적인 경로를 사용해야 합니다. 에이전트는 서로 다른 위치에서 실행되는 경우가 많으므로 현재 작업 디렉터리(./)에 절대 의존하지 마십시오. Path(__file__).parent를 사용하면 스크립트 디렉터리를 기준 경로로 가져올 수 있습니다.

from pathlib import Path

# Get absolute path relative to THIS script's location
SCRIPT_DIR = Path(__file__).parent
DATA_DIR = SCRIPT_DIR / 'data'
OUTPUT_DIR = SCRIPT_DIR / 'output'

# Always resolve to absolute path before use
config = DATA_DIR / 'config.json'
print('Config path:', config.resolve())

# Check if file exists before reading
if config.exists():
    import json
    with open(config, 'r', encoding='utf-8') as f:
        settings = json.load(f)
else:
    print(f'Config not found at {config.resolve()}')
    settings = {}

# Safe output path
result_path = (OUTPUT_DIR / 'result.json').resolve()
print('Will write to:', result_path)

빠른 확인: 컨텍스트 관리자

파일 입출력 모범 사례에 대한 이해도를 확인합니다.

파일 입출력 복습

이제 에이전트 코드에서 파일을 다루기 위한 탄탄한 기초를 갖추었습니다.

  • 읽을 때는 open('file', 'r', encoding='utf-8')를 사용하고, 쓸 때는 'w', 내용을 추가할 때는 'a'를 사용합니다
  • 파일이 닫히도록 항상 with 문을 사용합니다
  • pathlib.Path는 read_text()/write_text()를 통해 깔끔하고 플랫폼에 독립적인 경로 처리를 제공합니다
  • 구조화된 데이터에는 json.load(f) / json.dump(data, f, indent=2)를 사용합니다
  • 대용량 파일은 메모리 사용량을 줄이기 위해 한 줄씩 순회합니다
  • Path(__file__).parent를 기준 디렉터리로 사용하고, 현재 작업 디렉터리에 절대 의존하지 마십시오

자주 묻는 질문

“에이전트 환경에서 파일 읽기 및 쓰기” 강의는 무료인가요?

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

“에이전트 환경에서 파일 읽기 및 쓰기”에서 뭘 배우나요?

에이전트 도구에서 open(), pathlib.Path를 사용해 CSV/JSON/TXT 파일을 읽습니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“에이전트 환경에서 파일 읽기 및 쓰기” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

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