Python:[2]open讀寫檔案實現指令碼?

Python中檔案操作可以通過open函式,這的確很像C語言中的fopen。通過 open

函式獲取一個file object,然後呼叫read(),write()等方法對檔案進行讀寫

操作。

工具/原料

Python

open

使用open開啟檔案後一定要記得呼叫檔案物件的close()方法。比如可以用

try/finally語句來確保最後能關閉檔案。

Python:[2]open讀寫檔案實現指令碼

注:不能把open語句放在try塊裡,因為當開啟檔案出現異常時,檔案物件

file_object無法執行close()方法。

讀檔案

讀文字檔案

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

#第二個引數預設為r

input = open('data')

讀二進位制檔案

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

讀取所有內容

file_object = open('thefile.txt')

try:

all_the_text = file_object.read( )

finally:

file_object.close( )

讀固定位元組

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

寫檔案

寫文字檔案

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一次性寫入要高。

r 䣧以只讀模式開啟檔案

w 以只寫模式開啟檔案,且先把檔案內容清空(truncate the file first)

a 以新增模式開啟檔案,寫檔案的時候總是寫到檔案末尾,用seek也無用。打

開的檔案也是不能讀的

r+ 以讀寫方式開啟檔案,檔案可讀可寫,可寫到檔案的任何位置

w+ 和r+不同的是,它會truncate the file first

a+ 和r+不同的是,它只能寫到檔案末尾

檔案, 職業, 指令碼,
相關問題答案