Python io 讀取檔案

2021-08-06 07:24:58 字數 1356 閱讀 3269

python (io)讀取檔案

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)

python IO 檔案讀寫

io 由於cpu和記憶體的速度遠遠高於外設的速度,所以,在io程式設計中,就存在速度嚴重不匹配的問題。如要把100m的資料寫入磁碟,cpu輸出100m的資料只需要0.01秒,可是磁碟要接收這100m資料可能需要10秒,怎麼辦呢?有兩種辦法 第一種是cpu等著,也就是程式暫停執行後續 等100m的資料...

Python IO 檔案和目錄

操作檔案和目錄的函式一部分放在os模組中,一部分放在os.path模組中 檢視當前目錄的絕對路徑 os.path.abspath 在某個目錄下建立乙個新目錄,首先把新目錄的完整路徑表示出來 os.path.join e dir0 testdir e dir0 testdir 把兩個路徑合成乙個時,不...

python IO程式設計,檔案讀寫

函式 open name mode buffering 引數 返回 乙個檔案物件 例項 mode引數 r 唯讀。w 寫,原內容被替換。a 在原內容後追加內容。buffering引數 無緩衝,直接將資料寫到硬碟上。有緩衝,資料先寫到記憶體裡,只有使用flush函式或者close函式才會將資料更新到硬碟...