python学习日记 (练习20)

练习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、研究一下+=这个简写操作的作用。写一个脚本,在里边用一下这个操作符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值