您的位置:首页 > 编程语言 > Python开发

《笨办法学Python》 第20课手记

2016-01-22 22:04 591 查看

《笨办法学Python》 第20课手记

本节课讲函数与文件,内容比较简单,但请注意常见问题解答,你应该记住那些内容。

指针表示存储地址。

原代码如下:

from sys import argv #从sys模组中引入argv

script, input_file = argv #将argv的列表变量赋值给script和input_file

def print_all(f): #定义一个打印文件的函数
print f.read() #函数主体,打印从f变量中读取的内容

def rewind(f): #定义一个复读函数
f.seek(0) #函数主体使用seek设置文件(指针)的偏移。这里,作者想要你知道它的存在,看不懂先记住就好

def print_a_line(line_count, f): #定义一个只打印一行的函数,并将文件内部指针移向下一行
print line_count, f.readline()

current_file = open(input_file) #使用open函数打开文件,并赋值给curren_file(文件变量)

print "Now let's print the whole file:\n"

print_all(current_file) #调用函数print_all

print "Let's rewind, kind of like a tape."

rewind(current_file) #调用函数rewind,rewin读取的是文件内部的指针,而不是文件的指针

print "Let's print three lines:"

current_line = 1 #current_line表示行号的变量,首先置1
print_a_line(current_line, current_file)  #调用print_a_line函数,下同

current_line = current_line + 1 #行号加1
print_a_line(current_line, current_file)

current_line = current_line + 1 #行号加1
print_a_line(current_line, current_file)


结果如下:



本节课涉及的内容

Python中对于本节课涉及到的部分函数的解释:

使用 python -m podoc file 可查看,你需要按下回车以显示更多内容才能看到这里



seek函数:

file.seek(offset[, whence])

offset: 文件的读/写指针位置。

whence: 这是可选的,默认为0,这意味着绝对的文件定位,其他值是1,这意味着当前的位置和2手段寻求相对寻求相对文件的结束。

f.seek(0)表示将指针转移到文件的0byte位置,即开始位置。

readline读取一行之后会将文件内部的指针移向下一行,下次调用readline则会读取下一行位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: