Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python File Handling: สร้าง, อ่าน, เขียน, ลบ ไฟล์ คู่มือครบวงจร

Python File I/O ใช้ Built-in open() Function รองรับ Mode ต่างๆ สำหรับ Read, Write, Append

File Modes Cheatsheet

Modeคำอธิบายสร้างไฟล์ใหม่?Overwrite?
'r'Read (Default)❌-
'w'Write✅✅ (ลบข้อมูลเดิม)
'a'Append✅❌ (ต่อท้าย)
'x'Exclusive Create✅❌ (Error ถ้ามีอยู่แล้ว)
'r+'Read + Write❌❌
'b'Binary Mode (รวม: rb, wb, ab)--

1. สร้างไฟล์

# 'x' - สร้างใหม่ Error ถ้ามีอยู่แล้ว
with open("newfile.txt", "x") as f:
    pass  # สร้างไฟล์ว่าง

# 'w' - สร้างใหม่ (Overwrite ถ้ามีอยู่)
with open("newfile.txt", "w") as f:
    f.write("Initial content")

2. อ่านไฟล์

อ่านทั้งไฟล์

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

# Output: Hello!! Welcome to Python Goodbye.

อ่านบางส่วน (N Characters)

with open('somefile.txt', 'r') as f:
    print(f.read(5))  # "Hello"

อ่านทีละบรรทัด

# readline() - อ่าน 1 บรรทัด
with open('somefile.txt', 'r') as f:
    print(f.readline())  # "Hello!!\n"
    print(f.readline())  # "Welcome to Python\n"

# readlines() - อ่านทั้งหมดเป็น List
with open('somefile.txt', 'r') as f:
    lines = f.readlines()
    print(lines)  # ['Hello!!\n', 'Welcome to Python\n', 'Goodbye.\n']

# For Loop - Pythonic (Memory Efficient)
with open('somefile.txt', 'r') as f:
    for line in f:
        print(line.strip())  # strip() ลบ newline

3. เขียนไฟล์

เขียนไฟล์ใหม่ (Overwrite)

with open('writefile.txt', 'w', encoding='utf-8') as f:
    f.write("Write some content!")
    f.write("\nSecond line")

Append (ต่อท้ายไฟล์)

with open('writefile.txt', 'a', encoding='utf-8') as f:
    f.write("\nAppended line")

writelines() - เขียน List of Strings

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('writefile.txt', 'w') as f:
    f.writelines(lines)

4. ลบไฟล์

import os

file_path = "writefile.txt"

# ตรวจสอบก่อนลบ (ปลอดภัย)
if os.path.exists(file_path):
    os.remove(file_path)
    print("Deleted")
else:
    print("File not found")

# หรือใช้ try/except (EAFP - Easier to Ask Forgiveness than Permission)
try:
    os.remove(file_path)
except FileNotFoundError:
    print("File not found")

Best Practices

  • ✅ ใช้ with Statement - ปิดไฟล์อัตโนมัติ แม้มี Exception
  • ✅ ระบุ Encoding - encoding='utf-8' ป้องกันปัญหาภาษาไทย
  • ✅ Pathlib (Python 3.4+) - Object-oriented Path Handling

Pathlib Example (Modern Way)

from pathlib import Path

file_path = Path("data.txt")

# Write
file_path.write_text("Hello World", encoding='utf-8')

# Read
content = file_path.read_text(encoding='utf-8')

# Append
file_path.write_text(content + "\nNew line", encoding='utf-8')

# Delete
file_path.unlink(missing_ok=True)  # missing_ok=True ไม่ Error ถ้าไม่มีไฟล์

# Check exists
print(file_path.exists())

Binary Files (รูปภาพ, ไฟล์ Executable)

# Copy binary file
with open('source.jpg', 'rb') as src, open('dest.jpg', 'wb') as dst:
    dst.write(src.read())

# หรือใช้ shutil
import shutil
shutil.copy2('source.jpg', 'dest.jpg')

บทความเกี่ยวข้อง