from sys import argv
script, input_file = argv
# 定義print_all函數(shù)
def print_all(f):
# 打印文件全部?jī)?nèi)容
print(f.read())
# 定義函數(shù)rewind,參數(shù)f引用文件對(duì)象
def rewind(f):
# f。seek(0)是讓基準(zhǔn)點(diǎn)回到開(kāi)始位置
# 如果是seek(1),那就是讓基準(zhǔn)點(diǎn)回到當(dāng)前位置
# 如果是seek(2),那就是讓基準(zhǔn)點(diǎn)回到結(jié)束為止
f.seek(0)
# 定義函數(shù)print_a_line,參數(shù)line_count和f都是引用文件對(duì)象的
def print_a_line(line_count, f):
#f.readline()是一行一行讀取的
print(line_count, f.readline())
# 把文件input_file對(duì)象賦值給current_file
current_file = open(input_file)
# 打印
print("First let's print the whole file:\n")
# 調(diào)用函數(shù)print_all
print_all(current_file)
# 打印
print("Now let's rewind, kind of like a tape.")
# 調(diào)用函數(shù)rewind,作用就和倒帶差不多
rewind(current_file)
# 打印
print("Let's print three lines:")
# 把1賦值給current_line
current_line = 1
# 調(diào)用函數(shù)print_a_line
print_a_line(current_line, current_file)
# current_line自增
current_line = current_line + 1
# 調(diào)用print_a_line函數(shù)
print_a_line(current_line, current_file)
# 自增
current_line = current_line + 1
# 調(diào)用函數(shù)print_a_line
print_a_line(current_line, current_file)
第一次print_a_line被調(diào)用, current_line被賦值1
第二次print_a_line被調(diào)用, current_line被賦值2
第三次print_a_line被調(diào)用, current_line被賦值3