笨方法學python 習題20
阿新 • • 發佈:2021-01-12
技術標籤:python
習題20
python:3.9
#從sys庫呼叫argv
from sys import argv
#把argv解包,將引數依次賦予左邊的變數名
script,input_file=argv
#定義函式,形參f
def print_all(f):
#以只讀的方式讀取f中的內容並列印
print (f.read())
#定義函式,形參f
def rewind(f):
#移動檔案讀取指標至f中內容開頭的位置
f.seek(0)
#定義函式u,形參line_count,f
def print_a_line(line_count,f):
讀取f內容的一整行,並列印line_count和f中指定的內容
print (line_count,f.readline())
#開啟檔案讀取內容
current_file=open(input_file)
#列印並換行,首先列印整個檔案的內容
print("First let's print the whole file:\n")
#列印current_file的內容
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)
這裡我直接把第一題的答案打出來了,大家參考一下就行,如果有錯誤還請及時糾正我,下面是執行結果
PS C:\Users\78523\mybuff> python ex20.py test.txt
First let's print the whole file:
To all the people out there.
I say I don't like my hair.
I need to shave it off.
Now let's rewind,kind of like a tape.
Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to shave it off.
加分習題
-
通讀指令碼,在每行之前加上註解,以理解腳本里發生的事情。
答:同上 -
每次 print_a_line 執行時,你都傳遞了一個叫 current_line 的變數。在每次呼叫函式時,打印出 current_line 的至,跟蹤一下它在print_a_line 中是怎樣變成 line_count 的。
答 這裡其實 line_count 要叫做 位置引數,之所以呼叫時的引數 current_line 成為了函式定義時的 line_count 就是因為它們在定義與被呼叫時所處的位置是一樣的。
如果我們把函式定義時兩個引數的位置對調,並保持呼叫的順序不變。或者,函式定義時不變,呼叫時對調。都會因為行號這個整數(int) 麼有 readline() 這個方法而導致錯誤發生(以上是借用別的博主的文章,連結在這裡習題20 -
找出指令碼中每一個用到函式的地方。檢查 def 一行,確認引數沒有用錯。
-
上網研究一下 file 中的 seek 函式是做什麼用的。試著執行 pydoc file 看看能不能學到更多。
-
研究一下 += 這個簡寫操作符的作用,寫一個指令碼,把這個操作符用在裡邊試一下。
答+=:的意思為x+=y 就等於x=x+y