Python中操作文件之write()方法的使用教程
write()方法把字符串str寫入文件。沒有返回值。由于緩沖,字符串可能不實(shí)際顯示文件,直到flush()或close()方法被調(diào)用。
語法
以下是write()方法的語法:
fileObject.write( str )
參數(shù)
- str -- 這是要被寫入的文件中的字符串。
返回值
此方法不返回任何值。
例子
下面的例子顯示write()方法的使用。
#!/usr/bin/python
# Open a file in write mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(6):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
當(dāng)我們運(yùn)行上面的程序,它會(huì)產(chǎn)生以下結(jié)果:
Name of the file: foo.txt Line No 0 - This is 1st line Line No 1 - This is 2nd line Line No 2 - This is 3rd line Line No 3 - This is 4th line Line No 4 - This is 5th line Line No 5 - This is 6th line
相關(guān)文章
Django如何實(shí)現(xiàn)密碼錯(cuò)誤報(bào)錯(cuò)提醒
這篇文章主要介紹了Django如何實(shí)現(xiàn)密碼錯(cuò)誤報(bào)錯(cuò)提醒,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值2020-09-09
python3代碼輸出嵌套式對(duì)象實(shí)例詳解
在本篇文章里小編給大家整理了關(guān)于python3代碼輸出嵌套式對(duì)象實(shí)例詳解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2020-12-12
對(duì)Python 獲取類的成員變量及臨時(shí)變量的方法詳解
今天小編就為大家分享一篇對(duì)Python 獲取類的成員變量及臨時(shí)變量的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python直接調(diào)用和使用swig法方調(diào)用c++庫
這篇文章主要介紹了python直接調(diào)用和使用swig法方調(diào)用c++庫,c++運(yùn)算速度快于python,python簡單易寫。很多時(shí)候?qū)τ谝延械腸++代碼也不想用python重寫,此時(shí)就自然而然地想到用python調(diào)用c或者c++,兩全其美,需要的朋友可以參考一下2022-03-03
Python中eval帶來的潛在風(fēng)險(xiǎn)代碼分析
這篇文章主要介紹了Python中eval帶來的潛在風(fēng)險(xiǎn)代碼分析,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12

