Python3 File write() 方法
概述
write() 方法用於向檔中寫入指定字串。
在檔關閉前或緩衝區刷新前,字串內容存儲在緩衝區中,這時你在檔中是看不到寫入的內容的。
如果檔打開模式帶 b,那寫入檔內容時,str (參數)要用 encode 方法轉為 bytes 形式,否則報錯:TypeError: a bytes-like object is required, not 'str'。
語法
write() 方法語法如下:
fileObject.write( [ str ])
參數
-
str -- 要寫入檔的字串。
返回值
返回的是寫入的字元長度。
實例
檔 zaixian.txt 的內容如下:
1:www.xuhuhu.com 2:www.xuhuhu.com 3:www.xuhuhu.com 4:www.xuhuhu.com 5:www.xuhuhu.com
以下實例演示了 write() 方法的使用:
#!/usr/bin/python3 # 打開檔 fo = open("zaixian.txt", "r+") print ("檔案名: ", fo.name) str = "6:www.xuhuhu.com" # 在檔末尾寫入一行 fo.seek(0, 2) line = fo.write( str ) # 讀取檔所有內容 fo.seek(0,0) for index in range(6): line = next(fo) print ("檔行號 %d - %s" % (index, line)) # 關閉檔 fo.close()
以上實例輸出結果為:
檔行號 0 - 1:www.xuhuhu.com 檔行號 1 - 2:www.xuhuhu.com 檔行號 2 - 3:www.xuhuhu.com 檔行號 3 - 4:www.xuhuhu.com 檔行號 4 - 5:www.xuhuhu.com 檔行號 5 - 6:www.xuhuhu.com
查看檔內容:
$ cat zaixian.txt 1:www.xuhuhu.com 2:www.xuhuhu.com 3:www.xuhuhu.com 4:www.xuhuhu.com 5:www.xuhuhu.com 6:www.xuhuhu.com