Python 檔案 write() 方法

來源:互聯網
上載者:User

標籤:class   leo   使用   oob   run   傳回值   檔案的   div   重新整理   

概述

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

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

文法

write() 方法文法如下:

fileObject.write(str)
參數
  • 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() 方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.