练习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)

#重复太多,以后肯定用下面的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值