练习20 函数和文件:
# -*-coding:UTF-8 -*-
# 20:函数和文件
# 从sys库中导入argv方法
from sys import argv
# 解包,从argv中读取script,input_file
script, input_file = argv
# 定义方法:打印全部文件
def print_all(f):
print f.read()
# 定义方法:把指针放到第一行
# (因为L27的print_all方法把文件读取完了,需要把指针回文件的开始位置,
# 如果不设定的话,第三个方法中的readline()无法正常工作)
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)
运行结果:
PS H:\python\mystuff> 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、通读脚本,在每一行之前加上注释,以理解脚本里发生的事情。
# 完成
2、每次print_a_line运行时,你都传递了一个叫current_line的变量。每次调用函数时,打印出current_line的值,跟踪一下它在print_a_line中是怎样变成line_count的。
# 完成
3、找出脚本中每一个用到函数的地方。检查def一行,确认参数没有用错。
# 完成
4、上网研究一下file中的seek函数是做什么用的。试着运行pydoc file,看看能不能学到更多。
# 参考链接:http://www.runoob.com/python3/python3-file-seek.html
5、研究一下+=这个简写操作的作用。写一个脚本,在里边用一下这个操作符。