1.open
使用open打開文件后一定要記得調(diào)用文件對象的close()方法。比如可以用try/finally語句來確保最后能關(guān)閉文件。
file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )
注:不能把open語句放在try塊里,因為當打開文件出現(xiàn)異常時,文件對象file_object無法執(zhí)行close()方法。
2.讀文件
讀文本文件
input = open('data', 'r') #第二個參數(shù)默認為r input = open('data')
讀二進制文件
input = open('data', 'rb')
讀取所有內(nèi)容
file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )
讀固定字節(jié)
file_object = open('abinfile', 'rb') try: while True: chunk = file_object.read(100) if not chunk: break do_something_with(chunk) finally: file_object.close( )
讀每行
list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:
??? process line
3.寫文件
寫文本文件
output = open('data', 'w')
寫二進制文件
output = open('data', 'wb')
追加寫文件
output = open('data', 'w+')
寫數(shù)據(jù)
file_object = open('thefile.txt', 'w') file_object.write(all_the_text) file_object.close( )
寫入多行
file_object.writelines(list_of_text_strings)
注意,調(diào)用writelines寫入多行在性能上會比使用write一次性寫入要高。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
