Python 3.1 快速導覽 - 內建函數 open()

內建函數 (function) open() ,讀取檔案並回傳檔案串流物件,參數 (parameter) file 為檔名字串

函數描述
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)讀取檔案並回傳檔案串流物件


mode 有以下數種
'r'讀取(預設)
'w'寫入
'a'附加
'b'二進位模式
't'文字模式(預設)
'+'更新磁碟檔案
'U'通用新行模式


例如我們有以下的純文字檔案,檔名為 data.txt
He who has health has hope.
Liberty is the right to do everything which the laws allow.
Two heads are better than one.Misery loves company.
It is better to win the peace and to lose the war. 
God's mill grinds slow but sure.
It takes all sorts to make a world.There are two sides to every question. 
Rome was not built in a day.
Self-trust is the first secret of success.
Every man has his taste.
Experience is the extract of suffering.
Imagination is more important than knowledge.
The End


以下程式讀取 data.txt ,印出檔案物件、檔案物件的型態及 data.txt 的前四行
f = open("data.txt", "r")
print(f)
print(type(f))
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())

# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:open.py
# 功能:示範 Python 程式 
# 作者:張凱慶
# 時間:西元 2010 年 12 月


執行結果如下



中英文術語對照
函數function
參數parameter


內建函數




沒有留言: