1 1.open使用open打開文件后一定要記得調用文件對象的close()方法。比如可以用try/finally語句來確保最后能關閉文件。 2 file_object = open('thefile.txt') 3 try: 4 all_the_text = file_object.read( ) 5 finally: 6 file_object.close( ) 7 注:不能把open語句放在try塊里,因為當打開文件出現異常時,文件對象file_object無法執行close()方法。 8 2.讀文件讀文本文件input = open('data', 'r') 9 #第二個參數默認為r 10 input = open('data') 11 12 讀二進制文件input = open('data', 'rb') 13 讀取所有內容file_object = open('thefile.txt') 14 try: 15 all_the_text = file_object.read( ) 16 finally: 17 file_object.close( ) 18 讀固定字節file_object = open('abinfile', 'rb') 19 try: 20 while True: 21 chunk = file_object.read(100) 22 if not chunk: 23 break 24 do_something_with(chunk) 25 finally: 26 file_object.close( ) 27 讀每行list_of_all_the_lines = file_object.readlines( ) 28 如果文件是文本文件,還可以直接遍歷文件對象獲取每行: 29 for line in file_object: 30 process line 31 3.寫文件寫文本文件output = open('data.txt', 'w') 32 寫二進制文件output = open('data.txt', 'wb') 33 追加寫文件output = open('data.txt', 'a') 34 35 output .write("\n都有是好人") 36 37 output .close( ) 38 39 寫數據file_object = open('thefile.txt', 'w') 40 file_object.write(all_the_text) 41 file_object.close( )