python累乘例题_“笨方法”学Python3,习题 20 。

笨方法”学Python3,习题 20:函数和文件

1、函数和文件是如何协作的 ?

一、基础代码

所写的代码:

from sys import argv

script, input_file = argv

def print_all(f):

print(f.read())

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 D:\代码> & D:/软件/python/python.exe d:/代码/ex20.py txtx.txt

First let's print the whole file:

Mary had a little lamb

It's fleece was white as snow

It was also tasty

Now let's rewind, kind of like a tape.

Let's print three lines:

1 Mary had a little lamb

2 It's fleece was white as snow

3 It was also tasty

二、巩固练习1、添加注释2、跟踪current_line的变化(即添加了打印其数值的代码)4、上网查找 seek 函数的作用5、研究+=这个简写操作符的作用,用其重写脚本

+=即将+和=写到一起,x+=y与x=x+y一样,有累加的作用将26-34行改为如上即可

总结:

1、函数内部可写入文件执行函数,参数为文件名,调用函数时就直接对文件进行了操作

2、seek 函数:

file.seek(off, whence=0):在文件中移动off个操作标记,off为正数,则往结束方向移动;off为负数,则往开始方向移动。如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置

3、+=累加;-=累减;*=累乘;/=累除

^ v ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值