Python open讀寫檔案實現指令碼

2021-05-28 04:34:37 字數 1745 閱讀 2765

zz:

python中檔案操作可以通過open函式,這的確很像c語言中的fopen。通過open函式獲取乙個file object,然後呼叫read(),write()等方法對檔案進行讀寫操作。

1.open

使用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()方法。

2.讀檔案

讀文字檔案

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

3.寫檔案

寫文字檔案

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

以寫方式開啟檔案,可向檔案寫入資訊。如檔案存在,則清空該檔案,再寫入新內容a

以追加模式開啟檔案(即一開啟檔案,檔案指標自動移到檔案末尾),如果檔案不存在則建立 r+

以讀寫方式開啟檔案,可對檔案進行讀和寫操作。w+

清除檔案內容,然後以讀寫方式開啟檔案。a+

以讀寫方式開啟檔案,並把檔案指標移到檔案尾。b

以二進位制模式開啟檔案,而不是以文字模式。該模式只對windows或dos有效,類unix的檔案是用二進位制模式進行操作的。

python open 檔案讀寫

一 python檔案讀寫的幾種模式 r,rb,w,wb 那麼在讀寫檔案時,有無b標識的的主要區別在 呢?1 檔案使用方式標識 r 預設值,表示從檔案讀取資料。w 表示要向檔案寫入資料,並截斷以前的內容 a 表示要向檔案寫入資料,新增到當前內容尾部 r 表示對檔案進行可讀寫操作 刪除以前的所有資料 r...

Python open讀寫檔案實現指令碼

python中檔案操作可以通過open函式,這的確很像c語言中的fopen。通過open函式獲取乙個file object,然後呼叫read write 等方法對檔案進行讀寫操作。1.open 使用open開啟檔案後一定要記得呼叫檔案物件的close 方法。比如可以用try finally語句來確保...

python open檔案 讀寫模式說明

r open for reading and writing.the stream is positioned at the beginning of the file.w open for reading and writing.the file is created if it does not...