您的位置:首页 > 其它

练习20——函数和文件

2016-07-08 16:13 489 查看
# -*- 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)

#重复太多,以后肯定用下面的for循环进行升级:
# for current_line in range(1,4):
#   print_a_line(current_line, current_file)

#**加分题**
# 1.通读脚本,在每行之前加上注解,以理解脚本里发生的事情。
# OK
# 2.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。
#在每次调用函数时,打印出 current_line 的值,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。
# current_line 传入print_a_line方法时,只是把值代入,在方法中这个值附到line_count上去,然后在方法中运算。
# 3.找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。
# OK
# 4.上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydoc file 看看能不能学到更多。
# 参考:http://www.runoob.com/python3/python3-file-seek.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: