3.1 建立檔案
當你以寫入模式 ('w')
或新增模式 ('a')
開檔時,檔案會自動建立。如果檔案已存在,'w'
模式會覆蓋其內容,而 'a'
模式則會將資料新增到檔案的尾端。
建立檔案的範例
file = open('example.txt', 'w') # 以寫入模式開啟檔案,若不存在則建立
file.write("This is a new file.\n")
file.close()
在這個範例中,檔案 example.txt
如果不存在就會被建立,並寫入字串 "This is a new file.\n"
。
你也可以建立一個完全空的檔案——只需開啟檔案並立即關閉即可。
建立空白檔案的範例
file = open('example.txt', 'w')
file.close()
請注意,如果以寫入模式開啟已存在的檔案,其所有內容都會被刪除。
3.2 寫入檔案
有兩種常見的方法可以用來將資料寫入檔案——write()
和 writelines()
。
write()
方法
write()
方法將字串寫入檔案。如果檔案以寫入模式 ('w')
開啟,內容會先被清除再寫入新資料。而如果是新增模式 ('a')
,新資料則會被寫到檔案尾端。
write()
使用範例:
# 以寫入模式開啟檔案
file = open('example.txt', 'w')
file.write("Hello, World!\n")
file.write("This is a test file.\n")
file.close()
writelines()
方法
writelines()
方法接受一個字串列表並將其寫入檔案。它不會自動加入換行符號,因此你需要自己在字串內加入。
writelines()
使用範例:
lines = ["First line.\n", "Second line.\n", "Third line.\n"]
# 以寫入模式開啟檔案
file = open('example.txt', 'w')
file.writelines(lines)
file.close()
檔案編碼
你可以在讀取或寫入文本檔案時指定編碼。這可透過命名參數 encoding
完成。
範例:
# 以 UTF-8 編碼開啟檔案進行寫入
file = open('example_utf8.txt', 'w', encoding='utf-8')
file.write("一些中文內容。\n")
file.write("More text in UTF-8.\n")
file.close()
我們稍後會討論檔案和文本的各種編碼,但你現在應該知道此參數的存在,使用它可以幫助你避免許多問題。
3.3 向檔案新增資料
像寫入檔案一樣簡單,你可以將資料新增到檔案的尾端。只需以新增模式 ('a')
開啟檔案,其餘部分會自動完成。
以下是一些範例:
在檔案尾端新增字串
此範例展示了如何以新增模式 ('a')
開啟檔案,並將多行文字新增到檔案尾端。
file = open('example.txt', 'a') # 以新增模式開啟檔案
file.write("This is a new line added to the file.\n")
file.write("Another line is appended.\n")
file.close() # 關閉檔案
新增字串列表到檔案尾端
此範例展示了如何使用 writelines()
方法,將字串列表新增到檔案尾端。
lines = [
"Appending first line from list.\n",
"Appending second line from list.\n",
"Appending third line from list.\n"
]
file = open('example.txt', 'a') # 以新增模式開啟檔案
file.writelines(lines) # 新增字串列表
file.close() # 關閉檔案
以指定編碼新增字串
此範例展示了如何以指定的編碼(例如 UTF-8)開啟檔案並新增字串。
# 以指定編碼開啟檔案並新增資料
file = open('example_utf8.txt', 'a', encoding='utf-8')
file.write("新增一行文字,使用 UTF-8 編碼。\n")
file.write("又新增了一行文字。\n")
file.close() # 關閉檔案
你看,是不是超簡單!
GO TO FULL VERSION