標籤:class leo 使用 oob run 傳回值 檔案的 div 重新整理
概述
Python 檔案 write() 方法用於向檔案中寫入指定字串。
在檔案關閉前或緩衝區重新整理前,字串內容儲存在緩衝區中,這時你在檔案中是看不到寫入的內容的。
文法
write() 方法文法如下:
fileObject.write(str)
參數
傳回值
該方法沒有傳回值。
執行個體
檔案 runoob.txt 的內容如下:
1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com
以下執行個體示範了 write() 方法的使用:
#!/usr/bin/python3# 開啟檔案fo = open("runoob.txt", "r+",encoding="utf-8")print ("檔案名稱: ", fo.name)# 在檔案末尾寫入一行fo.seek(0,2)fo.write("\n6:www.runoob.com")# 讀取檔案所有內容fo.seek(0,0)for index in range(6): line = next(fo) print ("檔案行號 %d - %s" % (index, line))# 關閉檔案fo.close()
以上執行個體輸出結果為:
檔案行號 0 - 1:www.runoob.com檔案行號 1 - 2:www.runoob.com檔案行號 2 - 3:www.runoob.com檔案行號 3 - 4:www.runoob.com檔案行號 4 - 5:www.runoob.com檔案行號 5 - 6:www.runoob.com
查看檔案內容:
$ cat runoob.txt 1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com6:www.runoob.com
Python 檔案 write() 方法