笨方法”学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 ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯