Python中檔案操作可以通過open函數,這的确很像C語言中的fopen。通過open函數擷取一個file object,然後調用read(),write()等方法對檔案進行讀寫操作。
使用open打開檔案後一定要記得調用檔案對象的close()方法。比如可以用try/finally語句來確定最後能關閉檔案。

file_object = open('thefile.txt')

try:

all_the_text = file_object.read( )

finally:

file_object.close( )
注:不能把open語句放在try塊裡,因為當打開檔案出現異常時,檔案對象file_object無法執行close()方法。

input = open('data', 'r')

#第二個參數預設為r

input = open('data')

input = open('data', 'rb')






file_object = open('abinfile', 'rb')


while True:

chunk = file_object.read(100)

if not chunk:

break

do_something_with(chunk)



list_of_all_the_lines = file_object.readlines( )
如果檔案是文本檔案,還可以直接周遊檔案對象擷取每行:

for line in file_object:

process line

output = open('data', 'w')

output = open('data', 'wb')

output = open('data', 'w+')

file_object = open('thefile.txt', 'w')

file_object.write(all_the_text)

file_object.close( )

file_object.writelines(list_of_text_strings)
注意,調用writelines寫入多行在性能上會比使用write一次性寫入要高。
...
本文轉自CoderZh部落格園部落格,原文連結:http://www.cnblogs.com/coderzh/archive/2008/05/10/1191410.html,如需轉載請自行聯系原作者