Handling of Text Files文字檔案處理
Interactive study materials for EC7: reading, writing, deleting, updating records, and processing strings in Python.
EC7 互動學習材料:學習如何在 Python 中讀取、寫入、刪除、更新記錄及處理字串。
Learning Map學習地圖
This page follows the textbook sequence and turns the chapter into concept cards, code walk-throughs, quizzes, flashcards, and exam-style practice.
本頁按照課本章節次序,把內容轉化為概念卡、程式導讀、測驗、閃卡及考試式練習。
File Basics
檔案基礎
Modes, paths, streams, LF and EOF.
模式、路徑、串流、換行及檔案結尾。
Read Data
讀取資料
Use read, readline, and readlines.
使用 read、readline 及 readlines。
Write Data
寫入資料
Overwrite, append, remove files safely.
覆寫、追加及安全刪除檔案。
Record Systems
記錄系統
Load, search, delete, update, and add records.
載入、搜尋、刪除、更新及新增記錄。
Core Concepts核心概念
Why text files matter
文字檔的重要性
Text files store external data so a program can process large input without asking the user repeatedly. They are common in CSV, TXT and JSON workflows.
文字檔把資料儲存在程式外部,讓程式可處理大量輸入,而不用反覆要求使用者輸入。TXT、CSV、JSON 都是常見格式。
Stream idea
串流概念
Python reads a text file as a continuous character stream. A hidden pointer moves forward as characters or lines are read.
Python 會把文字檔視為連續字元串流。程式讀取字元或行時,隱藏指標會向前移動。
Opening modes開啟模式
| Mode 模式 | Description | 說明 |
|---|---|---|
"r" | Read an existing text file. Error if the file does not exist. | 讀取現有文字檔;檔案不存在會發生錯誤。 |
"x" | Create a new file. Error if the file already exists. | 建立新檔;若檔案已存在會發生錯誤。 |
"w" | Open and overwrite content; create the file if needed. | 開啟並覆寫內容;如檔案不存在則建立。 |
"a" | Open and append new content; create the file if needed. | 開啟並追加新內容;如檔案不存在則建立。 |
f = open("datafile.txt", "r")
content = f.read()
f.close()
Reading Content from Text Files從文字檔讀取內容
read()+Reads all remaining content from the current pointer position and returns one string.
由目前指標位置開始,讀取所有餘下內容,並以一個字串回傳。
f = open("inputfile.txt", "r")
content = f.read()
print(content)
print(type(content))
f.close()readline()+Reads one line up to and including the line feed character. If called at EOF, it returns an empty string.
讀取一行,直到包括換行字元為止;若已到檔案結尾,則回傳空字串。
line1 = f.readline()
line2 = f.readline()readlines()+Reads all remaining lines and returns a list of strings, often including line feed characters.
讀取所有餘下行,並回傳字串列表,通常每項仍包含換行字元。
lines = f.readlines()
# ["This is line one.\n", "This is line two.\n"]Checkpoint: reading until EOF
檢查點:讀到檔案結尾
member = []
f = open("NewMember.txt", "r")
name = f.readline()
while len(name) > 0:
member = member + [name]
name = f.readline()
f.close()The loop continues while the line read is not an empty string.
只要讀出的行不是空字串,迴圈便會繼續。
Writing and Deleting Text Files寫入及刪除文字檔
write()
Writes a string into the opened file. Mode "w" replaces old content; mode "a" appends after old content.
把字串寫入已開啟檔案。"w" 會取代舊內容;"a" 會在舊內容後追加。
f = open("outputfile.txt", "w")
f.write("This is new content.")
f.close()os.remove()
Deletes a file. Check that the file exists first to avoid a run-time error.
刪除檔案。應先檢查檔案是否存在,以避免執行時錯誤。
import os
if os.path.exists("targetfile.txt"):
os.remove("targetfile.txt")
else:
print("The file does not exist.")Encryption example
加密例子
The checkpoint shifts capital letters forward by X positions using ord() and chr(), while spaces remain unchanged.
檢查點使用 ord() 與 chr() 把大寫英文字母向後移動 X 位,而空格保持不變。
def encode(original_message, x):
encoded_message = ""
for i in range(0, len(original_message)):
if original_message[i] == " ":
encoded_char = 32
else:
encoded_char = ord(original_message[i]) + x
if encoded_char > 90:
encoded_char = encoded_char - 26
encoded_message += chr(encoded_char)
return encoded_messageString Processing字串處理
find()
Returns the first index of the target string, or -1 if not found. A start index may be supplied.
回傳目標字串第一次出現的索引;找不到則回傳 -1。可指定開始搜尋的位置。
the_string.find("is")
the_string.find("is", 3)split()
Splits a string into a list using whitespace or a chosen delimiter.
按空白或指定定界符把字串分割成列表。
"I am fine".split()
"cat#dog#bird".split("#")replace()
Returns a new string after replacement. It does not directly change the original string.
回傳替換後的新字串;不會直接更改原本字串。
s = "one two two three"
new_s = s.replace("two", "2", 1)CSV transformation workflow
CSV 轉換流程
Read lines, remove \n, split each row by comma, then convert number fields to integers.
讀取每行、移除 \n、按逗號分割每列,最後把數值欄位轉為整數。
fruits = f.readlines()
for i in range(0, len(fruits)):
fruits[i] = fruits[i].replace("\n", "")
fruits[i] = fruits[i].split(",")
fruits[i][1] = int(fruits[i][1])
fruits[i][2] = int(fruits[i][2])Updating Records in a Text File更新文字檔中的記錄
A structured text file can act like a simple database: each line is a record and each separated item is a field.
結構化文字檔可像簡單資料庫一樣運作:每行是一筆記錄,每個分隔項目是一個欄位。
Load and print
載入及列印
def load_record():
f = open("phonebook.txt", "r")
global record
record = f.readlines()
for i in range(0, len(record)):
record[i] = record[i].replace("\n", "")
record[i] = record[i].split(";")
f.close()Search, delete, add
搜尋、刪除、新增
def search_recordByFirstname(firstname):
for i in range(0, len(record)):
if record[i][0] == firstname:
return i
return -1
def add_record(firstname, lastname, noType, number):
f = open("phonebook.txt", "a")
f.write("\n" + firstname + ";" + lastname + ";" + noType + ";" + number)
f.close()Key reminder
重點提醒
After appending to the file, reload the file if the program also keeps a two-dimensional list in memory.
如果程式同時在記憶體中保存二維列表,追加檔案後應重新載入檔案以更新列表。
Interactive Quiz互動測驗
Choose one answer for each question, then submit to see your score and explanations.
每題選擇一個答案,提交後查看分數及解析。
3D Flashcards3D 閃卡
Click a card to flip it. Use these for quick recall before attempting the chapter exercises.
點擊卡片即可翻轉。可在做章末練習前用作快速複習。
Exam-Style Practice考試式練習
These questions are adapted from the chapter checkpoints and exercises. For open responses, click to reveal the reference answer.
以下題目改編自課本檢查點及章末練習。開放題可點擊查看參考答案。