《笨办法学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则会读取下一行位置。
相关文章推荐
- python核心编程-GUI程序之标签,按钮,进度条
- python操作RabbiMQ
- python核心编程-GUI程序按钮与标签
- Python 格式化字符分类
- Python操作MySQL数据库
- python模块系列之 - copy
- python--datetime&time
- [Python]Python pip用国内镜像下载的办法
- Python标准库:内置函数dict(**kwarg)
- 用Python操纵MySQL
- Python工具之SQLAlchemy
- 【LEETCODE】81-Search in Rotated Sorted Array II [Python]
- Python中urllib2总结
- python 中导入自己定义的模块路径
- python爬hdu网页
- Python学习笔记——基础篇(1): 变量及其类型
- python自动化渗透
- Python下载大全
- Python 高级特性之 sorted( )
- Python 高级特性之 filter( )