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

內建函數 (function) iter() ,回傳迭代器物件,通常用於檔案處理

函數描述
iter(object[, sentinel])回傳迭代器物件


例如我們有以下的純文字檔案,檔名為 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
with open("data.txt") as fp:
    for line in iter(fp.readline, "The End"):
        print(line)

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


執行結果如下



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


內建函數




沒有留言: