Python文件管理的中的讀寫文章簡介
在計算機的應用的過程中,Python文件管理和別的計算機語言相比更為簡單,如果你想了解Python文件管理怎樣應用某些模塊去進行文件的操作,你可以觀看我們的文章希望你從中能得到相關的知識。
介紹
你玩過的游戲使用文件來保存存檔;你下的訂單保存在文件中;很明顯,你早上寫的報告也保存在文件中。
幾乎以任何語言編寫的眾多應用程序中,文件管理是很重要的一部分。Python文件當然也不例外。在這篇文章中,我們將探究如何使用一些模塊來操作文件。我們會完成讀文件,寫文件,加文件內容的操作,還有一些另類的用法。
讀寫文件
最基本的文件操作當然就是在文件中讀寫數據。這也是很容易掌握的。現在打開一個文件以進行寫操作:
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt', 'w' )
fileHandle = open ( 'test.txt', 'w' )‘w'是指文件將被寫入數據,語句的其它部分很好理解。下一步就是將數據寫入文件:
- view plaincopy to clipboardprint?
- fileHandle.write ( 'This is a test.\nReally, it is.' )
- fileHandle.write ( 'This is a test.\nReally, it is.' )
這個語句將“This is a test.”寫入文件的***行,“Really, it is.”寫入文件的第二行。***,我們需要做清理工作,并且關閉Python文件管理:
- view plaincopy to clipboardprint?
- fileHandle.close()
fileHandle.close()正如你所見,在Python的面向對象機制下,這確實非常簡單。需要注意的是,當你再次使用“w”方式在文件中寫數據,所有原來的內容都會被刪除。如果想保留原來的內容,可以使用“a”方式在文件中結尾附加數據:
- 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()
以上語句將讀取整個文件并顯示其中的數據。我們也可以讀取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()
以上就是對Python文件管理的介紹,望大家有所收獲。
【編輯推薦】