Python入門示例系列24 檔案讀寫

2022-09-18 21:09:10 字數 2135 閱讀 8599

python入門示例系列24 檔案讀寫

檔案操作的模式如下表:

使用 open 開啟檔案後一定要記得呼叫檔案物件的 close() 方法。比如可以用 try/finally 語句來確保最後能關閉檔案。

file_object = open(r'd:\test.txt')

try:

all_the_text =file_object.read( )

finally:

file_object.close( )

print(all_the_text)

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

讀文字檔案方式開啟檔案

file_object = open(r'd:\test.txt'

, 'r')

#第二個引數預設為 r

file_object = open(r'd:\test.txt'

)讀二進位制檔案方式開啟檔案

file_object= open(r'd:\test.txt'

, 'rb')

讀取所有內容

file_object = open(r'd:\test.txt')

try:

all_the_text =file_object.read( )

finally:

file_object.close( )

print(all_the_text)

讀固定位元組

file_object = open(r'd:\test.txt', 'rb')

try:

whiletrue:

chunk = file_object.read(100)

if notchunk:

break

#do_something_with(chunk)

finally:

file_object.close( )

讀每行 readlines

file_object = open(r'd:\test.txt', 'r') 

list_of_all_the_lines = file_object.readlines( )

print(list_of_all_the_lines)

file_object.close( )

file_object = open(r'd:\test.txt', 'r')

for line infile_object:

print(line)

file_object.close( )

寫文字檔案方式開啟檔案

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

寫二進位制檔案方式開啟檔案

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

追加寫檔案方式開啟檔案

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

寫資料

all_the_text="aaa\nbbb\nccc\n"file_object = open(r'd:\thefile.txt', 'w')

file_object.write(all_the_text)

file_object.close( )

寫入多行

all_the_text="aaa\nbbb\nccc\n"file_object = open(r'd:\thefile.txt', 'w')

file_object.writelines(all_the_text)

file_object.close( )

追加

file = r'd:\thefile

.txt'with open(file, 'a+') as f:

f.write('aaaaaaaaaa\n')

ref

Python入門示例系列 目錄

系列目錄 python入門示例系列01 為什麼學python python入門示例系列02 python 語言的特點 python入門示例系列03 安裝python開發工具 python入門示例系列04 使用 idle shell python入門示例系列05 使用pycharm python入門示...

Python入門示例系列19 迴圈語句

python入門示例系列19 迴圈語句 python 中的迴圈語句有 for 和 while。python 中while 語句的一般形式 while 判斷條件 condition 執行語句 statements 同樣需要注意冒號和縮排。另外,在 python 中沒有 do.while 迴圈。以下例項...

java開發系列 spring簡單入門示例

1 jdk安裝 2 struts2簡單入門示例 前言 作為入門級的記錄帖,沒有過多的技術含量,簡單的搭建配置框架而已。這次講到spring,這個應該是ssh中的重量級框架,它主要包含兩個內容 控制反轉 依賴注入,和aop面向切面程式設計。控制反轉意思就是說,當我們呼叫乙個方法或者類時,不再有我們主動...