📁 การทำงานกับไฟล์ใน Python

เรียนรู้การอ่าน เขียน และจัดการไฟล์ในโปรแกรม Python

📖เกริ่นนำ: ทำไมต้องทำงานกับไฟล์?

การทำงานกับไฟล์เป็นทักษะสำคัญในการเขียนโปรแกรม เพราะข้อมูลส่วนใหญ่ถูกเก็บไว้ในไฟล์ เช่น:

💡 ข้อดีของการใช้ไฟล์:
  • Persistent Storage - ข้อมูลไม่หายหลังปิดโปรแกรม
  • Data Sharing - แชร์ข้อมูลระหว่างโปรแกรมต่างๆ
  • Backup - สามารถสำรองข้อมูลได้
  • Large Data - จัดการข้อมูลขนาดใหญ่ที่ไม่จุใน memory
project/
main.py
data.txt
config.json
logs/
app.log
data/
users.csv

🔑File Modes - โหมดการเปิดไฟล์

File Mode
โหมดไฟล์ - กำหนดว่าจะทำอะไรกับไฟล์
เมื่อเปิดไฟล์ต้องระบุ mode ว่าจะอ่าน (read), เขียน (write), หรือเพิ่มข้อมูล (append)
'r'
Read - อ่านไฟล์เท่านั้น (ค่าเริ่มต้น)
open('file.txt', 'r')

⚠️ ไฟล์ต้องมีอยู่ก่อน ไม่งั้นจะ error

'w'
Write - เขียนทับไฟล์
open('file.txt', 'w')

⚠️ ลบข้อมูลเดิมหมด! สร้างไฟล์ใหม่ถ้าไม่มี

'a'
Append - เพิ่มข้อมูลท้ายไฟล์
open('file.txt', 'a')

✅ ไม่ลบข้อมูลเดิม เพิ่มท้ายไฟล์

'r+'
Read + Write - อ่านและเขียน
open('file.txt', 'r+')

⚠️ ไฟล์ต้องมีอยู่ก่อน

'w+'
Write + Read - เขียนและอ่าน
open('file.txt', 'w+')

⚠️ ลบข้อมูลเดิมหมด!

'a+'
Append + Read - เพิ่มและอ่าน
open('file.txt', 'a+')

✅ ปลอดภัย ไม่ลบข้อมูล

⚠️ ระวัง! Mode 'w' และ 'w+' จะลบข้อมูลในไฟล์ทั้งหมดทันที! ถ้าไม่แน่ใจให้ใช้ 'a' หรือ 'r+' แทน

📖Reading Files - การอ่านไฟล์

วิธีเปิดไฟล์ที่ถูกต้อง: ใช้ with statement

✅ วิธีที่ถูกต้อง - ใช้ with

with open('file.txt', 'r') as file: content = file.read() print(content) # ไฟล์ปิดอัตโนมัติ!

✅ ไฟล์ปิดเองแม้เกิด error
✅ โค้ดสั้นและปลอดภัย

❌ วิธีเก่า - ต้องปิดเอง

file = open('file.txt', 'r') content = file.read() print(content) file.close() # ต้องปิดเอง # อันตราย: ถ้า error ไฟล์ไม่ปิด!

❌ ถ้าเกิด error ไฟล์จะไม่ปิด
❌ ต้องจำปิดไฟล์เอง

วิธีอ่านไฟล์

1. read() - อ่านทั้งไฟล์

# อ่านทั้งไฟล์เป็น string เดียว with open('story.txt', 'r', encoding='utf-8') as file: content = file.read() print(content) # อ่านแค่ N ตัวอักษรแรก with open('story.txt', 'r') as file: first_100 = file.read(100) # อ่าน 100 ตัวแรก print(first_100)
💡 เมื่อไรใช้ read(): เหมาะกับไฟล์เล็กที่ต้องการอ่านทั้งหมดพร้อมกัน

2. readline() - อ่านทีละบรรทัด

# อ่านบรรทัดแรก with open('data.txt', 'r') as file: line1 = file.readline() line2 = file.readline() line3 = file.readline() print("บรรทัดที่ 1:", line1) print("บรรทัดที่ 2:", line2) print("บรรทัดที่ 3:", line3) # อ่านจนกว่าจะหมดไฟล์ with open('data.txt', 'r') as file: while True: line = file.readline() if not line: # ถ้าไม่มีบรรทัดแล้ว break print(line.strip()) # strip() ตัด \n ออก
💡 เมื่อไรใช้ readline(): เมื่อต้องการประมวลผลทีละบรรทัด หรืออ่านแค่บางบรรทัด

3. readlines() - อ่านเป็น List

# อ่านทั้งไฟล์เป็น list ของ strings with open('names.txt', 'r') as file: lines = file.readlines() print(f"มีทั้งหมด {len(lines)} บรรทัด") # แสดงแต่ละบรรทัด for i, line in enumerate(lines, 1): print(f"บรรทัด {i}: {line.strip()}") # ตัวอย่าง: นับคำในไฟล์ with open('essay.txt', 'r') as file: lines = file.readlines() total_words = sum(len(line.split()) for line in lines) print(f"จำนวนคำทั้งหมด: {total_words}")
💡 เมื่อไรใช้ readlines(): เมื่อต้องการเก็บทุกบรรทัดไว้ในหน่วยความจำพร้อมกัน

4. Loop - วนลูปอ่านไฟล์ (แนะนำ!)

# ✅ วิธีที่ดีที่สุด - ประหยัด memory with open('big_file.txt', 'r') as file: for line in file: print(line.strip()) # ตัวอย่าง: หาบรรทัดที่มีคำว่า "error" with open('log.txt', 'r') as file: for line_num, line in enumerate(file, 1): if "error" in line.lower(): print(f"พบ error ที่บรรทัด {line_num}: {line.strip()}") # ตัวอย่าง: กรองข้อมูล with open('scores.txt', 'r') as file: high_scores = [] for line in file: score = int(line.strip()) if score >= 80: high_scores.append(score) print(f"คะแนนสูง: {high_scores}")
✅ ทำไมต้องใช้ Loop:
  • ประหยัด memory - ไม่โหลดทั้งไฟล์
  • เร็วกว่า readlines() สำหรับไฟล์ใหญ่
  • เหมาะกับไฟล์หลายล้านบรรทัด
# ตัวอย่างการอ่านไฟล์พร้อม error handling def read_file_safely(filename): """อ่านไฟล์อย่างปลอดภัย""" try: with open(filename, 'r', encoding='utf-8') as file: content = file.read() return content except FileNotFoundError: print(f"❌ ไม่พบไฟล์: {filename}") return None except PermissionError: print(f"❌ ไม่มีสิทธิ์อ่านไฟล์: {filename}") return None except Exception as e: print(f"❌ เกิดข้อผิดพลาด: {e}") return None # การใช้งาน content = read_file_safely('data.txt') if content: print("✅ อ่านไฟล์สำเร็จ") print(content)

✍️Writing Files - การเขียนไฟล์

การสร้างไฟล์ใหม่

# สร้างไฟล์ใหม่ด้วย mode 'w' with open('output.txt', 'w', encoding='utf-8') as file: file.write("สวัสดีครับ\n") file.write("นี่คือบรรทัดที่ 2\n") file.write("นี่คือบรรทัดที่ 3\n") print("✅ สร้างไฟล์สำเร็จ") # เขียนหลายบรรทัดด้วย writelines() lines = [ "บรรทัดที่ 1\n", "บรรทัดที่ 2\n", "บรรทัดที่ 3\n" ] with open('multiple_lines.txt', 'w') as file: file.writelines(lines)

การเขียนข้อมูลหลายประเภท

# เขียนตัวเลขและข้อมูลอื่นๆ with open('data.txt', 'w') as file: name = "สมชาย" age = 25 score = 95.5 # ต้องแปลงเป็น string ก่อนเขียน file.write(f"ชื่อ: {name}\n") file.write(f"อายุ: {age}\n") file.write(f"คะแนน: {score}\n") # เขียน list with open('fruits.txt', 'w') as file: fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม"] for fruit in fruits: file.write(f"{fruit}\n") # เขียน dictionary with open('student.txt', 'w') as file: student = { "name": "สมหญิง", "age": 20, "grade": "A" } for key, value in student.items(): file.write(f"{key}: {value}\n")
⚠️ ระวัง! Mode 'w' จะลบข้อมูลเดิมทั้งหมด! ถ้าต้องการเก็บข้อมูลเดิมไว้ให้ใช้ mode 'a' (append)

Appending to Files - การเพิ่มข้อมูลท้ายไฟล์

# เพิ่มข้อมูลท้ายไฟล์โดยไม่ลบข้อมูลเดิม with open('log.txt', 'a') as file: file.write("บรรทัดใหม่ที่เพิ่มเข้าไป\n") # ตัวอย่าง: เขียน log file import datetime def write_log(message): """เขียน log พร้อมเวลา""" timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open('app.log', 'a') as file: file.write(f"[{timestamp}] {message}\n") # การใช้งาน write_log("โปรแกรมเริ่มทำงาน") write_log("ผู้ใช้ล็อกอิน: user123") write_log("บันทึกข้อมูลสำเร็จ") # ตัวอย่าง: เพิ่มข้อมูลจาก user def add_todo(task): """เพิ่มงานใน todo list""" with open('todos.txt', 'a') as file: file.write(f"- {task}\n") return f"✅ เพิ่มงาน: {task}" print(add_todo("ซื้อของ")) print(add_todo("ทำการบ้าน")) print(add_todo("ออกกำลังกาย"))
Mode 'w'
ลบข้อมูลเดิม
VS
Mode 'a'
เพิ่มท้ายไฟล์

🔄Updating Files - การแก้ไขไฟล์

การแก้ไขไฟล์ที่มีอยู่แล้วต้องทำ 3 ขั้นตอน:

1. อ่านไฟล์
2. แก้ไขข้อมูล
3. เขียนทับ

ตัวอย่างการแก้ไขไฟล์

# แก้ไขคำในไฟล์ def replace_word_in_file(filename, old_word, new_word): """แทนที่คำในไฟล์""" try: # 1. อ่านไฟล์ with open(filename, 'r', encoding='utf-8') as file: content = file.read() # 2. แก้ไข new_content = content.replace(old_word, new_word) # 3. เขียนทับ with open(filename, 'w', encoding='utf-8') as file: file.write(new_content) return f"✅ แก้ไข '{old_word}' เป็น '{new_word}' แล้ว" except FileNotFoundError: return f"❌ ไม่พบไฟล์ {filename}" # การใช้งาน print(replace_word_in_file('story.txt', 'เก่า', 'ใหม่')) # แก้ไขบรรทัดเฉพาะ def update_line(filename, line_number, new_line): """แก้ไขบรรทัดที่ระบุ""" try: # 1. อ่านทุกบรรทัด with open(filename, 'r') as file: lines = file.readlines() # 2. แก้ไขบรรทัดที่ต้องการ (index เริ่มที่ 0) if 0 <= line_number < len(lines): lines[line_number] = new_line + '\n' else: return "❌ เลขบรรทัดไม่ถูกต้อง" # 3. เขียนทับทั้งไฟล์ with open(filename, 'w') as file: file.writelines(lines) return f"✅ แก้ไขบรรทัด {line_number + 1} แล้ว" except FileNotFoundError: return f"❌ ไม่พบไฟล์ {filename}" # ลบบรรทัดที่มีคำที่ไม่ต้องการ def remove_lines_with_word(filename, word): """ลบบรรทัดที่มีคำที่ระบุ""" try: # 1. อ่านและกรอง with open(filename, 'r') as file: lines = file.readlines() # 2. เก็บเฉพาะบรรทัดที่ไม่มีคำที่ระบุ filtered_lines = [line for line in lines if word not in line] # 3. เขียนกลับ with open(filename, 'w') as file: file.writelines(filtered_lines) removed = len(lines) - len(filtered_lines) return f"✅ ลบ {removed} บรรทัด" except FileNotFoundError: return f"❌ ไม่พบไฟล์ {filename}"
⚠️ คำเตือน: การแก้ไขไฟล์จะเขียนทับข้อมูลเดิม ควร backup ไฟล์สำคัญก่อนแก้ไข

📊Working with CSV and JSON

CSV Files (Comma-Separated Values)

CSV
ไฟล์ตารางที่แยกด้วยเครื่องหมายจุลภาค
CSV เป็นรูปแบบไฟล์ที่นิยมใช้เก็บข้อมูลแบบตาราง เหมาะกับการนำเข้า/ส่งออกจาก Excel
import csv # อ่าน CSV with open('students.csv', 'r', encoding='utf-8') as file: csv_reader = csv.reader(file) # อ่านหัวตาราง headers = next(csv_reader) print("หัวตาราง:", headers) # อ่านข้อมูล for row in csv_reader: print(row) # เขียน CSV students = [ ["ชื่อ", "อายุ", "คะแนน"], ["สมชาย", 20, 85], ["สมหญิง", 21, 92], ["สมศักดิ์", 19, 78] ] with open('students.csv', 'w', encoding='utf-8', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(students) print("✅ บันทึก CSV สำเร็จ") # ใช้ DictReader/DictWriter (สะดวกกว่า) with open('students.csv', 'r', encoding='utf-8') as file: csv_reader = csv.DictReader(file) for row in csv_reader: print(f"{row['ชื่อ']} อายุ {row['อายุ']} คะแนน {row['คะแนน']}")

JSON Files (JavaScript Object Notation)

JSON
รูปแบบข้อมูลที่อ่านง่ายและใช้กันแพร่หลาย
JSON เก็บข้อมูลแบบ key-value คล้าย dictionary ใน Python เหมาะสำหรับ APIs และ config files
import json # อ่าน JSON with open('config.json', 'r', encoding='utf-8') as file: data = json.load(file) print(data) # เขียน JSON student = { "name": "สมชาย", "age": 20, "grades": [85, 90, 88], "address": { "city": "กรุงเทพ", "zipcode": "10110" } } with open('student.json', 'w', encoding='utf-8') as file: json.dump(student, file, ensure_ascii=False, indent=4) print("✅ บันทึก JSON สำเร็จ") # อ่าน JSON จาก string json_string = '{"name": "สมหญิง", "age": 21}' data = json.loads(json_string) print(data["name"]) # แปลง Python object เป็น JSON string person = {"name": "สมศักดิ์", "age": 25} json_string = json.dumps(person, ensure_ascii=False) print(json_string)

Best Practices - แนวทางที่ดี

✅ ควรทำ:
  1. ใช้ with statement เสมอ - ไฟล์ปิดอัตโนมัติ
  2. ระบุ encoding='utf-8' สำหรับไฟล์ภาษาไทย
  3. ใช้ try/except จัดการ FileNotFoundError
  4. ใช้ path ที่ชัดเจน ไม่ใช้ hard-coded paths
  5. Backup ไฟล์สำคัญก่อนแก้ไข
  6. ใช้ loop อ่านไฟล์ใหญ่แทน readlines()
  7. ปิดไฟล์ทันทีหลังใช้งานเสร็จ
❌ ไม่ควรทำ:
  1. เปิดไฟล์โดยไม่ใช้ with
  2. ใช้ mode 'w' โดยไม่คิด - จะลบข้อมูลเดิม
  3. ลืมปิดไฟล์ (ถ้าไม่ใช้ with)
  4. โหลดไฟล์ใหญ่ทั้งหมดเข้า memory
  5. ไม่จัดการ errors
  6. ไม่ระบุ encoding สำหรับภาษาไทย

ตัวอย่าง Complete File Handler Class

class FileHandler: """คลาสจัดการไฟล์อย่างครบถ้วน""" def __init__(self, filename): self.filename = filename def read(self): """อ่านไฟล์""" try: with open(self.filename, 'r', encoding='utf-8') as f: return f.read() except FileNotFoundError: return f"❌ ไม่พบไฟล์: {self.filename}" def write(self, content): """เขียนไฟล์ (ทับข้อมูลเดิม)""" try: with open(self.filename, 'w', encoding='utf-8') as f: f.write(content) return "✅ เขียนไฟล์สำเร็จ" except Exception as e: return f"❌ Error: {e}" def append(self, content): """เพิ่มข้อมูลท้ายไฟล์""" try: with open(self.filename, 'a', encoding='utf-8') as f: f.write(content) return "✅ เพิ่มข้อมูลสำเร็จ" except Exception as e: return f"❌ Error: {e}" def exists(self): """ตรวจสอบว่าไฟล์มีหรือไม่""" import os return os.path.exists(self.filename) # การใช้งาน handler = FileHandler('test.txt') if not handler.exists(): print("สร้างไฟล์ใหม่...") handler.write("สวัสดีครับ\n") print(handler.append("บรรทัดใหม่\n")) print(handler.read())

🎮ทดลองเขียนและอ่านไฟล์

📝 File Editor Simulator

จำลองการทำงานกับไฟล์ (ข้อมูลเก็บใน browser เท่านั้น ไม่ได้สร้างไฟล์จริง)

พร้อมทำงาน...