Python File write() 方法

Python File(檔) 方法 Python File(檔) 方法


概述

write() 方法用於向檔中寫入指定字串。

在檔關閉前或緩衝區刷新前,字串內容存儲在緩衝區中,這時你在檔中是看不到寫入的內容的。

如果檔打開模式帶 b,那寫入檔內容時,str (參數)要用 encode 方法轉為 bytes 形式,否則報錯:TypeError: a bytes-like object is required, not 'str'。

語法

write() 方法語法如下:

fileObject.write( [ str ])

參數

  • str -- 要寫入檔的字串。

返回值

返回的是寫入的字元長度。

實例

以下實例演示了 write() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打開檔

fo = open("test.txt", "w")
print "檔案名為: ", fo.name
str = "IT研修"
fo.write( str )

# 關閉檔

fo.close()

以上實例輸出結果為:

檔案名為:  test.txt

查看檔內容:

$ cat test.txt
IT研修

Python File(檔) 方法 Python File(檔) 方法