exercise 20
2018-01-01 本文已影响0人
不娶名字
from sys import argv
script, input_file = argv
# 定义print_all函数
def print_all(f):
# 打印文件全部内容
print(f.read())
# 定义函数rewind,参数f引用文件对象
def rewind(f):
# f。seek(0)是让基准点回到开始位置
# 如果是seek(1),那就是让基准点回到当前位置
# 如果是seek(2),那就是让基准点回到结束为止
f.seek(0)
# 定义函数print_a_line,参数line_count和f都是引用文件对象的
def print_a_line(line_count, f):
#f.readline()是一行一行读取的
print(line_count, f.readline())
# 把文件input_file对象赋值给current_file
current_file = open(input_file)
# 打印
print("First let's print the whole file:\n")
# 调用函数print_all
print_all(current_file)
# 打印
print("Now let's rewind, kind of like a tape.")
# 调用函数rewind,作用就和倒带差不多
rewind(current_file)
# 打印
print("Let's print three lines:")
# 把1赋值给current_line
current_line = 1
# 调用函数print_a_line
print_a_line(current_line, current_file)
# current_line自增
current_line = current_line + 1
# 调用print_a_line函数
print_a_line(current_line, current_file)
# 自增
current_line = current_line + 1
# 调用函数print_a_line
print_a_line(current_line, current_file)
第一次print_a_line被调用, current_line被赋值1
第二次print_a_line被调用, current_line被赋值2
第三次print_a_line被调用, current_line被赋值3