练习20——函数和文件
2016-07-08 16:13
489 查看
# -*- 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) #重复太多,以后肯定用下面的for循环进行升级: # for current_line in range(1,4): # print_a_line(current_line, current_file) #**加分题** # 1.通读脚本,在每行之前加上注解,以理解脚本里发生的事情。 # OK # 2.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。 #在每次调用函数时,打印出 current_line 的值,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。 # current_line 传入print_a_line方法时,只是把值代入,在方法中这个值附到line_count上去,然后在方法中运算。 # 3.找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。 # OK # 4.上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydoc file 看看能不能学到更多。 # 参考:http://www.runoob.com/python3/python3-file-seek.html
相关文章推荐
- 记录一个android的代码网址
- Linux下启动Oracle服务和监听程序
- Android Studio的内存泄漏检测与解决
- Oracle安装后的默认账号以及一些基本操作
- UVA - 10474 Where is the Marble?
- 【noip暑假tarjan专题】
- cocos2dx中的声音
- 删除vector指定下标的元素
- DAG图与拓扑排序
- Layer3 OSPF网络类型和LSA1、2
- 工作环境配置
- opencv等待函数
- Oracle中SUBSTR与SUBSTRB的区别
- ubuntu安装openssh-server 报依赖错误的解决过程 ubuntu自带的有openssh-client,所以可以通过 1 ssh username@host 来远程连接linux 可
- myeclipse+maven实现多模块项目struts+spring+mybatis
- django常用命令
- UVA - 10420 List of Conquests
- Python的作用域
- 一个简单的守护进程的编写
- 停止线程的两种方法