练习20:函数和文件操作的基本方法
2016-04-17 22:40
459 查看
代码:
python中函数的声明和定义方法:
实例:
open
作用:打开一个文件
用法:
close
作用:关闭一个文件
用法:
read
作用:读取一个文件的内容
用法:
write
作用:将数据写入一个文件
用法:
seek
作用:跳转文件读取磁头(我不知道怎么描述,姑且这样吧= =、)
用法:
exists(存在于os.path)
作用:检测文件是否存在
用法:exists(<文件路径>)
例:
输出:\nabc
输出:
abc
#-*- coding:utf-8 -*- from sys import argv # 从sys函数库调用argv模组 script, input_file = argv # 解包argv函数 def print_all(f): # 声明print_all函数 print f.read() # 对f对象调用read方法 def rewind(f): # 声明rewind函数 f.seek(0) # 对f对象调用seek方法 def print_a_line(line_count, f): # 声明print_a_line函数 print line_count, f.readline() #输出行号和f变量指向文件的一行内容//readline方法:读取文件中一行的内容 current_file = open(input_file) # 打开input_file变量存储路径指向的文件并将file object赋值给current_file变量 print "First let's print the whole file:\n" # 提示 print_all(current_file) # 调用print_all函数 current_line = 1 # 声明并初始化current_line print_a_line(current_line, current_file) #调用print_a_line函数 current_line = current_line + 1 # current_line自加1 print_a_line(current_line, current_file) # 调用print_a_line函数 current_line = current_line + 1 # current_line自加1 print_a_line(current_line, current_file) # 调用print_a_line函数
函数
通过将源代码分为多个函数,可以增强函数的可读性和可维护性python中函数的声明和定义方法:
def 函数名1(<参数1>, <参数2>,........): 代码 代码 代码 def 函数名1(<参数1>, <参数2>,........): 代码 代码 代码
实例:
def print_all(f): # 声明print_all函数 print f.read() # 对f对象调用read方法读出文件内容并输出
文件操作基本函数
python文件操作的基本函数(其实是我已经学到的= =、)有:open,close,read,write,seek,existsopen
作用:打开一个文件
用法:
open(<file dir>, <model>),会返回一个file object用于对文件的后续操作
close
作用:关闭一个文件
用法:
close(<file object>)
read
作用:读取一个文件的内容
用法:
file_object.read()
write
作用:将数据写入一个文件
用法:
output_file_object.write(<要写入的数据>)
seek
作用:跳转文件读取磁头(我不知道怎么描述,姑且这样吧= =、)
用法:
file_object.seek(<要跳转的位置>)
exists(存在于os.path)
作用:检测文件是否存在
用法:exists(<文件路径>)
额外
在print要输出的字符串前加r可以使print直接输出字符串的原始数据而忽视其中的格式化字符(如果有的话)例:
print r'\nabc'
输出:\nabc
print '\nabc'
输出:
abc
相关文章推荐
- 节日 (201503-3)
- 在大字符串中返回一个子字符串的的位置
- 容器的思想
- Java断言
- image 圆角
- 单元素枚举类型实现Singleton
- vs plug
- 毕业设计今日总结(一)
- 【一天一道LeetCode】#21. Merge Two Sorted Lists
- 【一天一道LeetCode】#21. Merge Two Sorted Lists
- siegen程的android技能树之handler,looper,message
- cookie是指web浏览器存储的少量数据,该数据会在每次请求一个相关的URL时自动传到服务器中(转)
- 回归博客
- Samba服务详解
- pthread的条件变量初探
- samba,iptables
- WebStorm基本使用
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.
- 20145239杜文超 《Java程序设计》实验二 Java面向对象程序设计实验报告
- Set容器——HashSet及常用API