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

วิธีอ่านไฟล์ข้อความ (Text File) ใน Python

การอ่าน Text File ใน Python

Python มี built-in functions 3 วิธีสำหรับอ่านไฟล์ข้อความ

3 เมธอดหลัก

  • read(): อ่านทั้งไฟล์ คืนค่า string เดียว
  • readline(): อ่านทีละบรรทัด คืนค่า string
  • readlines(): อ่านทุกบรรทัด คืนค่า list of strings

ขั้นตอนการอ่านไฟล์

  1. เปิดไฟล์ด้วย open("filename.txt", "r") (r = read mode)
  2. ใช้เมธอดอ่านตามต้องการ
  3. ปิดไฟล์ด้วย close() หรือใช้ with statement (แนะนำ)

ตัวอย่าง: ใช้ with statement (Best Practice)

with open("myfile.txt", "r") as file:
    content = file.read()
    print("read():", content)

    file.seek(0)  # กลับไปต้นไฟล์
    print("readline():", file.readline())

    file.seek(0)
    print("readlines():", file.readlines())

ผลลัพธ์ตัวอย่าง

read(): This is an article on reading text files in Python.
Python has inbuilt functions to read a text file.
We can read files in three different ways.
Create a text file which you will read later.

readline(): This is an article on reading text files in Python.

readlines(): ['This is an article on reading text files in Python.\n',
              'Python has inbuilt functions to read a text file.\n',
              'We can read files in three different ways.\n',
              'Create a text file which you will read later.']

การอ่านบรรทัดต่อบรรทัด (Memory Efficient)

with open("large_file.txt", "r") as file:
    for line in file:
        process(line)  # ประมวลผลทีละบรรทัด

Encoding

ระบุ encoding สำหรับไฟล์ภาษาไทย: open("thai.txt", "r", encoding="utf-8")