回憶一下函數(shù)的要點(diǎn),然后一邊做這節(jié)練習(xí),一邊注意一下函數(shù)和文件是如何在一起協(xié)作發(fā)揮作用的。
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
特別注意一下,每次運(yùn)行 print_a_line 時(shí),我們是怎樣傳遞當(dāng)前的行號(hào)信息的。
$ python ex20.py test.txt
First let's print the whole file:
This is line 1
This is line 2
This is line 3
Now let's rewind, kind of like a tape.
Let's print three lines:
1 This is line 1
2 This is line 2
3 This is line 3
1.通讀腳本,在每行之前加上注解,以理解腳本里發(fā)生的事情。 2.每次 print_a_line 運(yùn)行時(shí),都傳遞了一個(gè)叫 current_line 的變量。在每次調(diào)用函數(shù)時(shí),打印出 current_line 的值,跟蹤一下它在 print_a_line 中是怎樣變成 line_count 的。 3.找出腳本中每一個(gè)用到函數(shù)的地方。檢查 def 一行,確認(rèn)參數(shù)沒(méi)有用錯(cuò)。 4.上網(wǎng)研究一下 file 中的 seek 函數(shù)是做什么用的。試著運(yùn)行 pydoc file 看看能不能學(xué)到更多。 5.研究一下+=這個(gè)簡(jiǎn)寫操作符的作用,寫一個(gè)腳本,把這個(gè)操作符用在里邊試一下。
f 就是一個(gè)變量,就好像在練習(xí) 18 中其他的變量一樣,只不過(guò)這次它代表了一個(gè)文件。 Python 中的文件就好像老舊的磁帶驅(qū)動(dòng)器,或者是像現(xiàn)在的 DVD 播放器。它有一個(gè) "磁頭",你可以在文件中"查找"到這個(gè)磁頭的位置,并且從那個(gè)位置開(kāi)始運(yùn)行。你每執(zhí)行一次 f.seek(0),就靠近文件的開(kāi)頭一點(diǎn)。每執(zhí)行一次 f.readline()你就從文件中讀取一行內(nèi)容,并且把“磁頭”移動(dòng)到文件末尾,換行符\n 的后面。繼續(xù)學(xué)習(xí)本書,你會(huì)看到更多的解釋。
函數(shù) readline() 返回一行以\n 結(jié)尾的文件內(nèi)容, 在你調(diào)用 print 函數(shù)的最后增加一個(gè)逗號(hào)',',用來(lái)避免為每一行添加兩個(gè)換行符\n。
首先,seek()方法是按字節(jié)而不是按行為處理單元的。代碼 seek(0)重新定位在文件的第 0 位(第一個(gè)字節(jié)處)。再次,current_line 是一個(gè)變量,在文件中沒(méi)有真正的意義可言。我們是在手動(dòng)的增加它的值。
你應(yīng)該知道在英語(yǔ)里我們可以簡(jiǎn)寫 "it is" 為 "it's",簡(jiǎn)寫 "you are" 為 "you're"。在英語(yǔ)里我們把這種寫法稱為縮寫,同樣的,+=是 =和 +兩個(gè)操作符的縮寫. 比如 x = x + y 可以縮寫為 x += y.
readline()內(nèi)部代碼是掃描文件的每一個(gè)字節(jié),直到找到一個(gè)\n 字符代碼,然后停止閱讀,并返回到此之前獲得的所有內(nèi)容。代碼中 f 的責(zé)任是在每次調(diào)用 readline()之后,維護(hù)“磁頭”在文件中的位置,以保證繼續(xù)讀后面的每一行。