📖 เกริ่นนำ: ทำไมต้องทำงานกับไฟล์?
การทำงานกับไฟล์เป็นทักษะสำคัญในการเขียนโปรแกรม เพราะข้อมูลส่วนใหญ่ถูกเก็บไว้ในไฟล์ เช่น:
📝 บันทึกข้อมูลผู้ใช้ (user data)
📊 เก็บผลการคำนวณหรือรายงาน
⚙️ อ่าน configuration files
📄 ประมวลผลเอกสาร CSV, JSON, หรือ text files
💾 บันทึก log files เพื่อติดตามการทำงานของโปรแกรม
💡 ข้อดีของการใช้ไฟล์:
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 ไฟล์จะไม่ปิด
❌ ต้องจำปิดไฟล์เอง
วิธีอ่านไฟล์
read()
readline()
readlines()
Loop
1. read() - อ่านทั้งไฟล์
with open ('story.txt' , 'r' , encoding='utf-8' ) as file:
content = file.read()
print (content)
with open ('story.txt' , 'r' ) as file:
first_100 = file.read(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())
💡 เมื่อไรใช้ readline(): เมื่อต้องการประมวลผลทีละบรรทัด หรืออ่านแค่บางบรรทัด
3. readlines() - อ่านเป็น List
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 - วนลูปอ่านไฟล์ (แนะนำ!)
with open ('big_file.txt' , 'r' ) as file:
for line in file:
print (line.strip())
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() สำหรับไฟล์ใหญ่
เหมาะกับไฟล์หลายล้านบรรทัด
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 - การเขียนไฟล์
การสร้างไฟล์ใหม่
with open ('output.txt' , 'w' , encoding='utf-8' ) as file:
file.write("สวัสดีครับ\n" )
file.write("นี่คือบรรทัดที่ 2\n" )
file.write("นี่คือบรรทัดที่ 3\n" )
print ("✅ สร้างไฟล์สำเร็จ" )
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
file.write(f"ชื่อ: {name}\n" )
file.write(f"อายุ: {age}\n" )
file.write(f"คะแนน: {score}\n" )
with open ('fruits.txt' , 'w' ) as file:
fruits = ["แอปเปิ้ล" , "กล้วย" , "ส้ม" ]
for fruit in fruits:
file.write(f" {fruit}\n" )
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" )
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 ("บันทึกข้อมูลสำเร็จ" )
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 :
with open (filename, 'r' , encoding='utf-8' ) as file:
content = file.read()
new_content = content.replace(old_word, new_word)
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 :
with open (filename, 'r' ) as file:
lines = file.readlines()
if 0 <= line_number < len (lines):
lines[line_number] = new_line + '\n'
else :
return "❌ เลขบรรทัดไม่ถูกต้อง"
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 :
with open (filename, 'r' ) as file:
lines = file.readlines()
filtered_lines = [line for line in lines if word not in line]
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
JSON Files
CSV Files (Comma-Separated Values)
CSV
ไฟล์ตารางที่แยกด้วยเครื่องหมายจุลภาค
CSV เป็นรูปแบบไฟล์ที่นิยมใช้เก็บข้อมูลแบบตาราง เหมาะกับการนำเข้า/ส่งออกจาก Excel
import 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)
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 สำเร็จ" )
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
with open ('config.json' , 'r' , encoding='utf-8' ) as file:
data = json.load(file)
print (data)
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 = '{"name": "สมหญิง", "age": 21}'
data = json.loads(json_string)
print (data["name" ])
person = {"name" : "สมศักดิ์" , "age" : 25 }
json_string = json.dumps(person, ensure_ascii=False )
print (json_string)
⭐ Best Practices - แนวทางที่ดี
✅ ควรทำ:
ใช้ with statement เสมอ - ไฟล์ปิดอัตโนมัติ
ระบุ encoding='utf-8' สำหรับไฟล์ภาษาไทย
ใช้ try/except จัดการ FileNotFoundError
ใช้ path ที่ชัดเจน ไม่ใช้ hard-coded paths
Backup ไฟล์สำคัญก่อนแก้ไข
ใช้ loop อ่านไฟล์ใหญ่แทน readlines()
ปิดไฟล์ทันทีหลังใช้งานเสร็จ
❌ ไม่ควรทำ:
เปิดไฟล์โดยไม่ใช้ with
ใช้ mode 'w' โดยไม่คิด - จะลบข้อมูลเดิม
ลืมปิดไฟล์ (ถ้าไม่ใช้ with)
โหลดไฟล์ใหญ่ทั้งหมดเข้า memory
ไม่จัดการ errors
ไม่ระบุ 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 เท่านั้น ไม่ได้สร้างไฟล์จริง)
ชื่อไฟล์:
เนื้อหาไฟล์:
✍️ เขียนไฟล์ (Write)
➕ เพิ่มท้ายไฟล์ (Append)
📖 อ่านไฟล์ (Read)
🗑️ ล้างไฟล์
พร้อมทำงาน...