Python文件管理的中的讀寫文章簡(jiǎn)介
在計(jì)算機(jī)的應(yīng)用的過程中,Python文件管理和別的計(jì)算機(jī)語(yǔ)言相比更為簡(jiǎn)單,如果你想了解Python文件管理怎樣應(yīng)用某些模塊去進(jìn)行文件的操作,你可以觀看我們的文章希望你從中能得到相關(guān)的知識(shí)。
介紹
你玩過的游戲使用文件來(lái)保存存檔;你下的訂單保存在文件中;很明顯,你早上寫的報(bào)告也保存在文件中。
幾乎以任何語(yǔ)言編寫的眾多應(yīng)用程序中,文件管理是很重要的一部分。Python文件當(dāng)然也不例外。在這篇文章中,我們將探究如何使用一些模塊來(lái)操作文件。我們會(huì)完成讀文件,寫文件,加文件內(nèi)容的操作,還有一些另類的用法。
讀寫文件
最基本的文件操作當(dāng)然就是在文件中讀寫數(shù)據(jù)。這也是很容易掌握的?,F(xiàn)在打開一個(gè)文件以進(jìn)行寫操作:
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt', 'w' )
fileHandle = open ( 'test.txt', 'w' )‘w'是指文件將被寫入數(shù)據(jù),語(yǔ)句的其它部分很好理解。下一步就是將數(shù)據(jù)寫入文件:
- view plaincopy to clipboardprint?
- fileHandle.write ( 'This is a test.\nReally, it is.' )
- fileHandle.write ( 'This is a test.\nReally, it is.' )
這個(gè)語(yǔ)句將“This is a test.”寫入文件的***行,“Really, it is.”寫入文件的第二行。***,我們需要做清理工作,并且關(guān)閉Python文件管理:
- view plaincopy to clipboardprint?
- fileHandle.close()
fileHandle.close()正如你所見,在Python的面向?qū)ο髾C(jī)制下,這確實(shí)非常簡(jiǎn)單。需要注意的是,當(dāng)你再次使用“w”方式在文件中寫數(shù)據(jù),所有原來(lái)的內(nèi)容都會(huì)被刪除。如果想保留原來(lái)的內(nèi)容,可以使用“a”方式在文件中結(jié)尾附加數(shù)據(jù):
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt', 'a' )
- fileHandle.write ( '\n\nBottom line.' )
- fileHandle.close()
- fileHandle = open ( 'test.txt', 'a' )
- fileHandle.write ( '\n\nBottom line.' )
- fileHandle.close()
讀寫文件
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt' )
- print fileHandle.read()
- fileHandle.close()
- fileHandle = open ( 'test.txt' )
- print fileHandle.read()
- fileHandle.close()
以上語(yǔ)句將讀取整個(gè)文件并顯示其中的數(shù)據(jù)。我們也可以讀取Python文件管理中的一行:
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt' )
- print fileHandle.rehttp://new.51cto.com/wuyou/adline()
- # "This is a test."
- fileHandle.close()
- fileHandle = open ( 'test.txt' )
- print fileHandle.readline() # "This is a test."
- fileHandle.close()
以上就是對(duì)Python文件管理的介紹,望大家有所收獲。
【編輯推薦】