Tag: open()

  • วิธีใช้ open() เพื่อทำงานกับไฟล์ใน Python: วิธีใช้งาน, วิธีเขียนโดยใช้ with และไม่ใช้ with, และ 4 modes ในการทำงานกับไฟล์ (+ bonus การลบไฟล์) พร้อมตัวอย่าง

    วิธีใช้ open() เพื่อทำงานกับไฟล์ใน Python: วิธีใช้งาน, วิธีเขียนโดยใช้ with และไม่ใช้ with, และ 4 modes ในการทำงานกับไฟล์ (+ bonus การลบไฟล์) พร้อมตัวอย่าง

    ในบทความนี้ เราจะมาดูวิธีใช้ open() เพื่อทำงานกับไฟล์ใน Python กัน:

    1. Intro to open(): วิธีการเขียนและการใช้งาน
    2. 4 modes: 4 วิธีการทำงานกับไฟล์
    3. Bonus: วิธีลบไฟล์

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 💻 Intro to open()
      1. 🔢 Syntax
      2. 🗄️ Using open()
    2. 🗂️ Mode
      1. 📄 Create
      2. 📖 Read
      3. ➕ Append
      4. ✏️ Write
    3. 🍩 Bonus: Delete
    4. ⚡ Summary
    5. 😺 GitHub
    6. 📃 References

    💻 Intro to open()

    .

    🔢 Syntax

    open() เป็น base function สำหรับทำงานกับไฟล์ และต้องการ 2 arguments:

    open(filename, mode)
    
    • filename = ชื่อไฟล์ (เป็น string เช่น "my_file.txt")
    • mode = mode ในการทำงานกับไฟล์ (เช่น "r" สำหรับอ่านไฟล์)

    .

    🗄️ Using open()

    เราสามารถใช้ open() ได้ 2 วิธี ได้แก่:

    วิธีที่ 1. เปิดไฟล์โดยไม่ใช้ with ซึ่งจะต้องมี .close() เพื่อปิดไฟล์เมื่อทำงานเสร็จ:

    # Open file
    file = open(filename, mode)
    
    # Act on file
    file.method()
    
    # Close file
    file.close()
    

    วิธีที่ 2. เปิดไฟล์โดยใช้ with:

    # Open file
    with open(filename, mode) as file:
        
        # Act on file
        file.method()
    

    วิธีที่ 2 เป็นวิธีที่นิยมใช้มากกว่า เพราะเราไม่จำเป็นต้องปิดไฟล์ด้วย .close() หลังทำงานเสร็จ


    🗂️ Mode

    open() มี 4 modes ในการทำงานกับไฟล์ ได้แก่:

    ModeActionNote
    "x"สร้างไฟล์แสดง error ถ้ามีไฟล์ชื่อเดียวกันอยู่แล้ว
    "r"อ่านไฟล์แสดง error ถ้ามีไม่มีไฟล์ที่ต้องการ
    "a"เพิ่มข้อมูลในไฟล์สร้างไฟล์ใหม่ถ้าไม่มีไฟล์ชื่อเดียวกันอยู่แล้ว
    "w"เขียนทับข้อมูลที่มีในไฟล์สร้างไฟล์ใหม่ถ้าไม่มีไฟล์ชื่อเดียวกันอยู่แล้ว

    ไปดูตัวอย่างการใช้ทั้ง 4 modes กัน

    .

    📄 Create

    ตัวอย่างการสร้างไฟล์ด้วย "x":

    # Create a file
    with open("example.txt", "x") as file:
        file.write("This is the first line.")
        file.write("This is the second line.")
        file.write("This is the third line.")
    

    ผลลัพธ์: เราจะได้ไฟล์ชื่อ example.txt ในเครื่องของเรา

    .

    📖 Read

    เราสามารถอ่านไฟล์ด้วย "r" ได้ 3 วิธี:

    วิธีที่ 1. ใช้ .read() เพื่ออ่านเนื้อหาทั้งหมด:

    # Read the file - all
    with open("example.txt", "r") as file:
        file.read()
    

    ผลลัพธ์ใน console:

    This is the first line.
    This is the second line.
    This is the third line.
    

    วิธีที่ 2. ใช้ .readline() ในกรณีที่ต้องการอ่านรายบรรทัด:

    # Read the file - one line at a time
    with open("example.txt", "r") as file:
        file.readline()
        file.readline()
    

    ผลลัพธ์ใน console:

    This is the first line.
    This is the second line.
    

    วิธีที่ 3. ใช้ for loop เพื่ออ่านเนื้อหาทั้งหมดทีละบรรทัด:

    # Read the file - line by line
    with open("example.txt", "r") as file:
        
        # Loop through each line
        for line in file:
            print(line)
    

    ผลลัพธ์ใน console:

    This is the first line.
    This is the second line.
    This is the third line.
    

    .

    ➕ Append

    ตัวอย่างการเพิ่มข้อมูลด้วย "a":

    # Add content to the file
    with open("example.txt", "a") as file:
        file.write("This is the fourth line.")
    

    เนื้อหาในไฟล์:

    This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.
    

    .

    ✏️ Write

    ตัวอย่างการเขียนไฟล์ด้วย "w":

    # Overwrite the file
    with open("example.txt", "w") as file:
        file.write("This is all there is now.")
    

    เนื้อหาในไฟล์:

    This is all there is now.
    

    🍩 Bonus: Delete

    ในกรณีที่เราต้องการลบไฟล์ เราจะต้องเรียกใช้ remove() function จาก os module:

    # Import os module
    import os
    
    # Delete the file
    os.remove("example.txt")
    

    ผลลัพธ์: ไฟล์จะถูกลบออกจากเครื่อง


    ⚡ Summary

    • open() เป็น base Python function สำหรับทำงานกับไฟล์
    • open() ต้องการ 2 arguments คือ:
      • filename: ชื่อไฟล์
      • mode: mode ในการทำงานกับไฟล์
    • วิธีใช้งาน:
      • open() มักใช้คู่กับ with
      • ถ้าไม่ใช้ with เราจะต้องปิดไฟล์ด้วย .close() เมื่อมช้งานเสร็จ
    • open() มี 4 modes ได้แก่:
      • "x": สร้างไฟล์
      • "r": อ่านไฟล์
      • "a": เพิ่มเนื้อหา
      • "w": เขียนทับข้อมูลเดิม
    • ลบไฟล์ด้วย os.remove()

    😺 GitHub

    ดูตัวอย่าง code ทั้งหมดได้ที่ GitHub


    📃 References