
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策制定
- Python - if 語句
- Python - if else
- Python - 巢狀 if
- Python - match-case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - while 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式與模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅限關鍵字引數
- Python - 位置引數
- Python - 僅限位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表項
- Python - 修改列表項
- Python - 新增列表項
- Python - 刪除列表項
- Python - 遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組項
- Python - 更新元組
- Python - 解包元組
- Python - 遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合項
- Python - 新增集合項
- Python - 刪除集合項
- Python - 遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典項
- Python - 修改字典項
- Python - 新增字典項
- Python - 刪除字典項
- Python - 字典檢視物件
- Python - 遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列項
- Python - 新增陣列項
- Python - 刪除陣列項
- Python - 遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類與物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤與異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 加入執行緒
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 同步執行緒
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - Socket 程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期與時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - Monkey Patching
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - 寫入檔案
寫入檔案涉及以特定模式開啟檔案,向其中寫入資料,然後關閉檔案以確保所有資料都被儲存並且資源被釋放。Python 提供了內建函式 `open()` 來處理檔案操作以及各種寫入資料的方法。
開啟檔案以進行寫入
開啟檔案以進行寫入是執行 Python 寫入操作的第一步。`open()` 函式用於以不同的模式開啟檔案,每種模式都適合於特定用例。
`open()` 函式
Python 中的 `open()` 函式用於開啟檔案。它至少需要一個引數,即檔名,並且可以接受一個可選的第二個引數,該引數指定應以何種模式開啟檔案。
寫入檔案的模式
以下是您可以用來開啟檔案以進行寫入的主要模式:
w(寫入模式)− 開啟檔案以進行寫入。如果檔案存在,則在寫入之前會截斷(清空)檔案。如果檔案不存在,則建立一個新檔案。
a(追加模式)− 資料寫入檔案的末尾。如果檔案不存在,則建立一個新檔案。
x(獨佔建立模式)− 開啟檔案以進行獨佔建立。如果檔案已存在,則操作失敗。
b(二進位制模式)− 與其他模式一起使用時,以二進位制模式開啟檔案。
+(更新模式)− 開啟檔案以進行更新(讀取和寫入)。
示例:以寫入模式開啟檔案
此模式用於當您希望將資料寫入檔案時,每次開啟檔案時都從頭開始:
file = open("example.txt", "w") file.write("Hello, World!") file.close() print ("File opened successfully!!")
以下是獲得的輸出:
File opened successfully!!
示例:以追加模式開啟檔案
此模式用於當您希望將資料新增到檔案的末尾而不更改其現有內容時:
file = open("example.txt", "a") file.write("Appending this line.\n") file.close() print ("File opened successfully!!")
這將產生以下結果:
File opened successfully!!
使用 write() 方法寫入檔案
write() 方法用於向檔案寫入單個字串。這使其適用於各種基於文字的檔案操作。
write() 方法接受一個引數:要寫入檔案的字串。它將字串的精確內容寫入檔案,不會新增任何其他字元,例如換行符。
示例
在下面的示例中,我們以寫入模式開啟檔案“example.txt”。然後,我們使用 write() 方法將字串寫入檔案:
# Open a file in write mode with open("example.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a new line.\n") print ("File opened successfully!!")
以上程式碼的輸出如下:
File opened successfully!!
使用 writelines() 方法寫入檔案
writelines() 方法用於將字串列表寫入檔案。列表中的每個字串都按順序寫入檔案,不會自動新增任何換行符。
示例
在這個例子中,我們建立了一個字串列表 lines,每個字串以換行符結尾。然後,我們以寫入模式開啟檔案“example.txt”,並使用 writelines() 方法一次性將列表中的所有字串寫入檔案:
# List of lines to write to the file lines = ["First line\n", "Second line\n", "Third line\n"] # Open a file in write mode with open("example.txt", "w") as file: file.writelines(lines) print ("File opened successfully!!")
獲得的輸出如下所示:
File opened successfully!!
寫入新檔案
在 Python 中寫入新檔案包括建立新檔案(或覆蓋現有檔案)並將所需內容寫入其中。在這裡,我們將解釋寫入新檔案所涉及的步驟:
開啟檔案 - 使用 open() 函式以寫入模式(“w”或二進位制檔案的“wb”)建立或開啟檔案。
寫入資料 - 使用 write() 或 writelines() 方法將資料寫入檔案。
關閉檔案 - 確保在寫入後正確關閉檔案,通常使用“with”語句進行自動處理。
示例
在下面的示例中,我們建立一個“foo.txt”檔案,並將給定的內容寫入該檔案,最後關閉該檔案:
# Open a file fo = open("foo.txt", "w") fo.write( "Python is a great language.\nYeah its great!!\n") # Close opened file fo.close()
如果您使用任何文字編輯器應用程式(例如記事本)開啟此檔案,它將包含以下內容:
Python is a great language. Yeah its great!!
以二進位制模式寫入新檔案
預設情況下,對檔案物件的讀/寫操作是在文字字串資料上執行的。如果我們需要處理不同型別的檔案,例如媒體檔案 (mp3)、可執行檔案 (exe) 或圖片 (jpg),則必須透過在讀/寫模式前新增“b”字首以二進位制模式開啟檔案。
將二進位制資料寫入檔案
要將二進位制資料寫入檔案,請以二進位制寫入模式 ('wb') 開啟檔案。以下示例演示了這一點:
# Open a file in binary write mode with open('test.bin', 'wb') as f: # Binary data data = b"Hello World" f.write(data)
將文字字串轉換為位元組
可以使用 encode() 函式將文字字串轉換為位元組。當您需要將文字資料作為二進位制資料寫入時,這很有用:
# Open a file in binary write mode with open('test.bin', 'wb') as f: # Convert text string to bytes data = "Hello World".encode('utf-8') f.write(data)
寫入現有檔案
當以寫入模式 ('w') 開啟現有檔案時,其先前的內容將被擦除。使用寫入許可權開啟檔案將其視為新檔案。要將資料新增到現有檔案而不擦除其內容,應以追加模式 ('a') 開啟檔案。
示例
以下示例演示如何以追加模式開啟檔案並向其中新增新文字:
# Open a file in append mode fo = open("foo.txt", "a") text = "TutorialsPoint has a fabulous Python tutorial" fo.write(text) # Close opened file fo.close()
如果您使用任何文字編輯器應用程式(例如記事本)開啟此檔案,它將包含以下內容:
Python is a great language. Yeah its great!! TutorialsPoint has a fabulous Python tutorial
以讀寫模式寫入檔案
當使用 'w' 或 'a' 開啟檔案進行寫入時,無法在檔案的任何較早位元組位置執行寫入操作。但是,'w+' 模式允許讀寫操作而無需關閉檔案。seek() 函式用於將讀/寫指標移動到檔案中的任何所需位元組位置。
使用 seek() 方法
seek() 方法用於設定檔案內讀/寫指標的位置。seek() 方法的語法如下:
fileObject.seek(offset[, whence])
其中:
offset - 這是檔案內讀/寫指標的位置。
whence - 這是可選的,預設為 0,這意味著絕對檔案定位;其他值為 1,表示相對於當前位置查詢;2 表示相對於檔案結尾查詢。
示例
以下程式演示如何以讀寫模式 ('w+') 開啟檔案,寫入一些資料,查詢特定位置,然後覆蓋檔案內容的一部分:
# Open a file in read-write mode fo = open("foo.txt", "w+") # Write initial data to the file fo.write("This is a rat race") # Move the read/write pointer to the 10th byte fo.seek(10, 0) # Read 3 bytes from the current position data = fo.read(3) # Move the read/write pointer back to the 10th byte fo.seek(10, 0) # Overwrite the existing content with new text fo.write('cat') # Close the file fo.close()
如果我們以讀取模式開啟檔案(或在 'w+' 模式下跳轉到起始位置)並讀取內容,它將顯示以下內容:
This is a cat race