python(檔案讀取寫入)

2021-08-04 19:32:19 字數 1380 閱讀 6283

python讀寫檔案

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

python讀取 寫入檔案

python程式設計 從入門到實踐 讀書筆記 1.讀取檔案並且對檔案內容進行列印有三種方式 with open test.txt as fo for lins in fo print lins.rstrip with open test.txt as fo lines fo.read print l...

python 寫入 讀取txt檔案

with open desc.txt w as f f.write 我是個有想法的小公舉 這句 自帶檔案關閉功能。比較常用的檔案讀寫選項 r 以讀的方式開啟,只能讀檔案,若檔案不存在,則發生異常 w 以寫的方式開啟,只能寫檔案,如果檔案不存在,建立該檔案 如果檔案已存在,先清空,再開啟檔案 rb 以...

python的檔案讀取寫入

讀寫檔案是最常見的io操作。python內建了讀寫檔案的函式,用法和c是相容的。讀寫檔案前,我們先必須了解一下,在磁碟上讀寫檔案的功能都是由作業系統提供的,現代作業系統不允許普通的程式直接操作磁碟,所以,讀寫檔案就是請求作業系統開啟乙個檔案物件 通常稱為檔案描述符 然後,通過作業系統提供的介面從這個...