首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 檔案操作:write() 方法寫入字串完整教學

     編輯:更多程式設計知識

write() 方法將字串寫入檔案。因作業系統緩衝機制,資料可能暫時停留在記憶體,需呼叫 flush() 或 close() 確保落盤。本文詳細說明語法、參數、編碼、緩衝與實戰範例。

語法


fileObject.write(str)
  • str:要寫入的字串(Python 3 為 str,Python 2 為 str/unicode,二進位模式下為 bytes)。
  • 不自動添加換行符,需自行在字串末尾加 \n。

回傳值

Python 3 回傳寫入的 字元數(文字模式)或 位元組數(二進位模式);Python 2 無回傳值(None)。

範例 1:基本寫入與讀回


with open('foo.txt', 'w') as f:
    f.write('Line 1\n')
    f.write('Line 2\n')
    f.write('Line 3\n')

with open('foo.txt', 'r') as f:
    print(f.read())
# 輸出:
# Line 1
# Line 2
# Line 3

範例 2:附加模式寫入


with open('foo.txt', 'a') as f:
    f.write('Appended Line\n')

範例 3:二進位模式寫入位元組


data = b'\x00\x01\x02\x03'
with open('binary.dat', 'wb') as f:
    f.write(data)

範例 4:配合 seek 從檔案末尾寫入


with open('foo.txt', 'r+') as f:
    f.seek(0, 2)  # 移至檔案末尾 (whence=2 代表從末尾)
    f.write('New Last Line\n')

完整示範腳本(含讀回驗證)


#!/usr/bin/python
with open('foo.txt', 'w+') as f:
    print("Name:", f.name)
    # 預設內容
    for i in range(1, 6):
        f.write(f'Line {i}\n')

    # 從末尾新增一行
    f.seek(0, 2)
    f.write('Line 6\n')

    # 從頭讀回驗證
    f.seek(0)
    for i, line in enumerate(f):
        print(f"Line No {i} - {line.rstrip()}")

# 輸出:
# Name: foo.txt
# Line No 0 - Line 1
# Line No 1 - Line 2
# Line No 2 - Line 3
# Line No 3 - Line 4
# Line No 4 - Line 5
# Line No 5 - Line 6

關鍵注意事項

情境說明
緩衝資料先進 OS 緩衝區,flush() 強制寫入磁碟,close() 自動 flush。
編碼文字模式預設編碼 locale.getpreferredencoding(),建議明確指定 encoding='utf-8'。
換行轉換Windows 文字模式下 \n 自動轉 \r\n,二進位模式不轉換。
非字串物件需先轉字串(str(obj)、json.dumps、pickle 等),否則拋 TypeError。

write() vs writelines()

  • write(str):單一字串。
  • writelines(seq):字串可迭代物件(列表、產生器),不自動加換行,需自行在元素中包含 \n。

總結

write() 是檔案輸出最基礎的方法。掌握模式選擇(w/a/r+/wb)、編碼指定、緩衝控制與指標定位,能精準處理各類檔案寫入需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved