Data Files: reading and writing text files Data Files: การอ่านและเขียนไฟล์ข้อความ
Learn open / write / read / append / readline / readlines / splitlines and the context manager (with) เรียนรู้ open / write / read / append / readline / readlines / splitlines และ Context Manager (with)
Programs often need to save or load text from a file, not just the keyboard and screen as in
Input and Output. In Python you open a file with open(filename, mode) — mode
'w' to write fresh, 'r' to read, and 'a' to append — then work with
the file and close it with close(). It is best to use with open(...) as f: (a context
manager), because it closes the file for you automatically when the block ends.
โปรแกรมมักต้องเก็บหรือโหลดข้อความจากไฟล์ ไม่ใช่แค่คีย์บอร์ดกับจออย่างในบท Input and Output
ใน Python เปิดไฟล์ด้วย open(ชื่อไฟล์, โหมด) — โหมด 'w' สำหรับเขียนใหม่,
'r' สำหรับอ่าน และ 'a' สำหรับต่อท้าย (append) —
จากนั้นทำงานกับไฟล์แล้วปิดด้วย close()
แนะนำใช้ with open(...) as f: (Context Manager) เพราะเมื่อจบบล็อกจะปิดไฟล์ให้อัตโนมัติ
Ways to read content from a file วิธีอ่านเนื้อหาจากไฟล์
read()— reads the whole file as one stringreadline()— reads one line (usually keeps the\n)readlines()— reads every line into a list (each usually keeps its\n)read().splitlines()— gives a list with the trailing\nremoved
read()— อ่านทั้งไฟล์เป็นสตริงเดียวreadline()— อ่านหนึ่งบรรทัด (มักรวม\n)readlines()— อ่านทุกบรรทัดเป็น list (แต่ละตัวมักมี\n)read().splitlines()— ได้ list โดยตัด\nออกจากท้ายบรรทัด
1 Write text to a file with open / write / close 1 เขียนข้อความลงไฟล์ด้วย open / write / close
Use open(path, 'w') to open a file for writing, then f.write(...) writes a string to
it. A \n in the string means a new line, and you must call f.close() when done. After a
successful Run there is a download link for the .txt file written.
ใช้ open(path, 'w') เพื่อเปิดไฟล์สำหรับเขียน จากนั้น f.write(...) เขียนสตริงลงไฟล์
ตัวอักษร \n ในสตริงหมายถึงขึ้นบรรทัดใหม่ และต้องเรียก f.close() เมื่อใช้เสร็จ
หลังกด Run สำเร็จ จะมีลิงก์ดาวน์โหลดไฟล์ .txt ที่เขียนไว้
wrote file.txt
2 Write with a context manager (with) 2 เขียนด้วย Context Manager (with)
Use with open(...) as f: as a context manager — when the indented block ends, Python calls
close() for you. So you do not write f.close() yourself, and you are less likely to
forget to close the file. After a successful Run you can download file2.txt.
ใช้ with open(...) as f: เป็น Context Manager — เมื่อจบบล็อกย่อหน้า Python จะเรียก close() ให้อัตโนมัติ
จึงไม่ต้องเขียน f.close() เอง และลดโอกาสลืมปิดไฟล์
หลังกด Run สำเร็จ สามารถดาวน์โหลด file2.txt ได้
wrote file2.txt
3 Read the whole file with read() 3 อ่านทั้งไฟล์ด้วย read()
Use open(..., 'r') to open for reading and f.read() to read all the
content as one string. You may optionally pick a .txt file before Run — it is read
by JavaScript in the browser (never uploaded) and used as file.txt.
ใช้ open(..., 'r') เพื่อเปิดอ่าน และ f.read() เพื่ออ่านทั้งเนื้อหาเป็นสตริงเดียว
เลือกไฟล์ .txt จากเครื่องก่อนกด Run — ระบบอ่านด้วย JavaScript ในเบราว์เซอร์ (ไม่เก็บขึ้นเซิร์ฟเวอร์)
แล้วใช้เนื้อหานั้นเป็น file.txt
Line 1 Line 2
Note: the code above simulates Python syntax (open / read etc.). Run works through
JavaScript in the browser; when you upload a .txt, its content is used as file.txt
(the write in the example is demo syntax and will not overwrite the file you chose) — nothing
is sent to a server.
หมายเหตุ: โค้ดด้านบนเป็นการจำลองไวยากรณ์ Python (open / read ฯลฯ)
การกด Run ทำงานผ่าน JavaScript ในเบราว์เซอร์ เมื่ออัปโหลด .txt แล้ว ระบบจะใช้เนื้อหาที่อ่านได้เป็น file.txt
(ส่วน write ในตัวอย่างเป็นไวยากรณ์สาธิต จะไม่ทับไฟล์ที่เลือก) — ไม่ส่งไฟล์ไปเซิร์ฟเวอร์
4 Read the first line with readline() 4 อ่านบรรทัดแรกด้วย readline()
Use readline() to read one line from the file's current position. The result
usually keeps the newline \n at the end (if the file has one). Optionally choose a .txt
file before Run.
ใช้ readline() เพื่ออ่านหนึ่งบรรทัดจากตำแหน่งปัจจุบันของไฟล์
ผลลัพธ์มักรวมเครื่องหมายขึ้นบรรทัดใหม่ \n ไว้ท้ายสตริงด้วย (ถ้ามีในไฟล์)
เลือกไฟล์ .txt ก่อนกด Run
Line 1
Note: Python syntax simulated with JavaScript in the browser; a .txt file is read with
FileReader and never uploaded.
หมายเหตุ: จำลองไวยากรณ์ Python ด้วย JavaScript ในเบราว์เซอร์ อ่านไฟล์ .txt ด้วย FileReader ไม่เก็บขึ้นเซิร์ฟเวอร์
5 Read all lines into a list with readlines() 5 อ่านทุกบรรทัดเป็น list ด้วย readlines()
Use readlines() to read every line and return a list of strings. Each item usually
keeps its trailing \n — reach one by index, e.g. lines[0]. Without a mode,
open('file.txt') opens for reading ('r') by default.
ใช้ readlines() เพื่ออ่านทุกบรรทัดแล้วคืนค่าเป็น list ของสตริง
แต่ละสมาชิกมักมี \n ท้ายบรรทัด — เข้าถึงด้วยดัชนีเช่น lines[0]
ถ้าไม่ระบุโหมด open('file.txt') จะเปิดแบบอ่าน ('r') เป็นค่าเริ่มต้น
['Line 1\n', 'Line 2\n'] index 0: Line 1 index 1: Line 2
Note: Python syntax simulated with JavaScript in the browser; a .txt file is read with
FileReader and never uploaded.
หมายเหตุ: จำลองไวยากรณ์ Python ด้วย JavaScript ในเบราว์เซอร์ อ่านไฟล์ .txt ด้วย FileReader ไม่เก็บขึ้นเซิร์ฟเวอร์
6 Read into a list without newlines using splitlines() 6 อ่านเป็น list โดยตัด newline ด้วย splitlines()
Use f.read().splitlines() to read the whole file and split it into a list of lines. The string
method splitlines() removes the trailing \n from each line, unlike
readlines(), which usually keeps it.
ใช้ f.read().splitlines() เพื่ออ่านทั้งไฟล์แล้วแยกเป็น list ของบรรทัด
โดยเมธอด splitlines() ของสตริงจะตัด \n ออกจากท้ายแต่ละบรรทัด
ต่างจาก readlines() ที่มักยังเก็บ \n ไว้
['Line 1', 'Line 2'] index 0: Line 1 index 1: Line 2
Note: Python syntax simulated with JavaScript in the browser; a .txt file is read with
FileReader and never uploaded.
หมายเหตุ: จำลองไวยากรณ์ Python ด้วย JavaScript ในเบราว์เซอร์ อ่านไฟล์ .txt ด้วย FileReader ไม่เก็บขึ้นเซิร์ฟเวอร์
7 Add line numbers — write numbered lines to a new file 7 Add Line Numbers — ใส่เลขบรรทัดลงไฟล์ใหม่
Read a source file with readlines(), then write a new file in the form number: text
using a for loop and a counter n starting at 1. After Run you can download
notes_numbered.txt.
อ่านไฟล์ต้นทางด้วย readlines() แล้วเขียนไฟล์ใหม่ในรูปแบบ เลข: ข้อความ
โดยใช้ลูป for และตัวนับ n เริ่มที่ 1
หลัง Run สามารถดาวน์โหลด notes_numbered.txt ได้
1: Hello 2: World 3: Python
Practice — from the "add line numbers" file แบบฝึก — จากไฟล์ใส่เลขบรรทัด
Suppose notes.txt has these 3 lines (no upload needed):
สมมติไฟล์ notes.txt มีเนื้อหา 3 บรรทัดดังนี้ (ไม่ต้องอัปโหลดไฟล์):
- Line 1:
Hello - Line 2:
World - Line 3:
Python
- บรรทัดที่ 1:
Hello - บรรทัดที่ 2:
World - บรรทัดที่ 3:
Python
Hello World Python
The idea of the program:
แนวคิดของโปรแกรม:
with open('notes.txt', 'r') as src:
lines = src.readlines()
with open('notes_numbered.txt', 'w') as out:
n = 1
for line in lines:
out.write(f'{n}: {line}')
n = n + 1
Q1: From the file above (line 1 = Hello, line 2 = World, line 3 = Python), what should line 2 of the output file notes_numbered.txt be?
ข้อ 1: จากไฟล์ด้านบน (บรรทัดที่ 1 = Hello, บรรทัดที่ 2 = World, บรรทัดที่ 3 = Python) บรรทัดที่ 2 ของไฟล์ผลลัพธ์ notes_numbered.txt ควรเป็นอะไร?
Q2: From the same file, if you call lines = src.readlines(), what is lines[0] roughly?
ข้อ 2: จากไฟล์เดียวกัน ถ้าเรียก lines = src.readlines() ค่าประมาณของ lines[0] คืออะไร?
8 Append — add data to the end of a file 8 Append — ต่อท้ายข้อมูลในไฟล์
Mode 'a' (append) opens a file to write at the end without erasing the existing
content, unlike 'w', which starts writing from an empty file.
โหมด 'a' (append) เปิดไฟล์เพื่อเขียนต่อท้ายโดยไม่ลบเนื้อหาเดิม
ต่างจาก 'w' ที่เริ่มเขียนใหม่จากไฟล์ว่าง
start more
9 Reverse lines — reverse the line order in a file 9 Reverse Lines — กลับลำดับบรรทัดในไฟล์
Read the content of input.txt as a list of lines, then write it in reverse order to a new file
output.txt. Use the slice lines[::-1] to reverse the list.
อ่านเนื้อหาจาก input.txt เป็น list ของบรรทัด แล้วเขียนกลับลำดับไปยังไฟล์ใหม่ output.txt
ใช้สไลซ์ lines[::-1] เพื่อกลับลำดับ list
C B A
Note: Run on this page is a JavaScript simulation, not real Python. The reading examples
(Demos 3–6) read a .txt only with JavaScript in the browser, never uploaded. The
write / append / reverse examples can be downloaded as a .txt (Blob) after a
successful Run. For real Python, try
Google Colab.
หมายเหตุ: การกด Run บนหน้านี้เป็นการจำลองด้วย JavaScript ไม่ใช่ Python จริง
ตัวอย่างอ่านไฟล์ (Demo 3–6) อ่าน .txt ด้วย JavaScript ในเบราว์เซอร์เท่านั้น ไม่เก็บขึ้นเซิร์ฟเวอร์
ตัวอย่างเขียน / append / reverse หลัง Run สำเร็จสามารถดาวน์โหลดเป็นไฟล์ .txt (Blob) ได้
หากต้องการทดลอง Python จริง แนะนำ
Google Colab
References References / แหล่งอ้างอิง
Sources used for this lesson:
แหล่งที่ใช้ประกอบเนื้อหาในบทนี้:
-
Reading and Writing Files —
Tutorial — Reading and Writing Files
(
open, modes, and the basic methods) (open, โหมด, และเมธอดพื้นฐาน) -
open()— Built-in Functions — open (opening a file, incl. modesr/w/a) (เปิดไฟล์ รวมโหมดr/w/a) -
File object methods —
io.TextIOBase
(
read/readline/readlines/write) -
str.splitlines()— Built-in Types — splitlines (split lines, removing the newline) (แยกบรรทัดโดยตัด newline) -
The
withstatement — Compound statements — with (Context Manager)