การอ่านและเขียนไฟล์ในบริบทของตัวแทน
open(), pathlib.Path และการอ่านไฟล์ CSV/JSON/TXT จากเครื่องมือตัวแทน
การอ่านและเขียนไฟล์ในบริบทของตัวแทน เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
เหตุใดการรับส่งข้อมูลไฟล์จึงสำคัญต่อเอเจนต์
เอเจนต์จำเป็นต้องอ่านการกำหนดค่า เก็บผลลัพธ์ระหว่างทาง และเขียนรายงานผลลัพธ์อยู่บ่อยครั้ง Python มีสองวิธีหลักในการทำงานกับไฟล์ ได้แก่ ฟังก์ชัน open() ในตัว และโมดูล pathlib สมัยใหม่ ทั้งสองอย่างเป็นพื้นฐานที่จำเป็นต้องรู้
การดำเนินการกับไฟล์ทุกครั้งควรใช้ตัวจัดการบริบท (คำสั่ง 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()
ฟังก์ชัน 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)การเขียนไฟล์ด้วย open()
ใช้โหมด '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.load() เพื่อแยกวิเคราะห์ไฟล์ JSON และใช้ json.dump() เพื่อเขียนไฟล์ ควรใช้ indent=2 เสมอเพื่อให้ผลลัพธ์อ่านได้ง่ายสำหรับมนุษย์ และใช้ ensure_ascii=False เพื่อคงอักขระ Unicode ไว้
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)การทำงานกับไฟล์ไบนารี
ใช้โหมด 'rb' เพื่ออ่านไฟล์ไบนารี เช่น รูปภาพ PDF และเสียง และใช้ 'wb' เพื่อเขียนไฟล์เหล่านั้น อย่าพยายามถอดรหัสเนื้อหาไบนารีเป็นข้อความ ให้ใช้ read_bytes()/write_bytes() กับ pathlib หรือใช้โหมดไบนารีร่วมกับ 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)การจัดการปัญหาการเข้ารหัสและอักขระขึ้นบรรทัดใหม่
ระบบแต่ละระบบใช้อักขระขึ้นบรรทัดใหม่แตกต่างกัน (\n บน Linux/macOS และ \r\n บน Windows) ควรระบุ encoding='utf-8' เสมอ และปล่อยให้ Python จัดการอักขระขึ้นบรรทัดใหม่ด้วย newline=None (ค่าเริ่มต้น) สำหรับไฟล์ที่มี 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เป็นไดเรกทอรีฐานของคุณ อย่าพึ่งพา cwd
คำถามที่พบบ่อย
บทเรียน “การอ่านและเขียนไฟล์ในบริบทของตัวแทน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การอ่านและเขียนไฟล์ในบริบทของตัวแทน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การอ่านและเขียนไฟล์ในบริบทของตัวแทน”
open(), pathlib.Path และการอ่านไฟล์ CSV/JSON/TXT จากเครื่องมือตัวแทน คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การอ่านและเขียนไฟล์ในบริบทของตัวแทน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม
ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การอ่านและเขียนไฟล์ในบริบทของตัวแทน
- การไล่สำรวจไดเรกทอรีและค้นหาไฟล์
- การจัดการรูปแบบไฟล์: CSV, JSON และ TXT
- การดำเนินการกับไฟล์อย่างปลอดภัยพร้อมจัดการข้อผิดพลาด