您的位置:首页 > 其它

练习20:函数和文件操作的基本方法

2016-04-17 22:40 459 查看
代码:

#-*- 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,exists

open

作用:打开一个文件

用法:
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: