###############################python文件操作##########################################
1,文件读写的认识:
1)python 内置了读写文件的函数,用法和c是兼容的
2)操作系统不允许普通的程序直接操作磁盘,所以,读写文件:请求操作系统打开一个文件对象(又称文件描述符),然后,通过操作系统提供的接口从这个文件对象操作;
2,文件读写的方式:
1)- 打开文件 f = open('filename',mode)
open函数的模式(mode)
r 以读的方式打开,定位到文件开头 , 默认的 mode
r+ 以读写的方式打开,定位文件开头 , 可以写入内容到文件
w 以写的方式打开,打开文件的时候会清空文件的内容,并且不能读
w+ 以读写的方式打开,定位到文件头,并且打开文件的时候也会清空文件的内容,如果文件没有,会建立一个。
a 以写的方式打开,定位到文件的末尾,是一个追加的操作 , 但并不允许读
a+ 以读写的方式打开,定位到文件的末尾,追加的方式。
在使用以上 mode 打开文件的时候,如果增加了b 模式,表示以二进制方式打开
**示例:
f = open('elepha')
f = open('elepha','w') ###会删除源文件内容,重新写入'hello'到文件中
2)- 对文件操作 :read,write,readlines,writelines,readline
示例:
f.write('hello')
3)- 关闭文件 f.close()
f.close()
3,文件的其他操作
f.flush()
f.seek(x,y) ##x,表示偏移量。0,不偏移;>0,向右偏移量;<0,向左偏移量。
##y,偏移开始位置。0,从开始的位置;1,从当前的位置;2,从末尾
4.with关键字(打开后,操作完毕后,自动关闭)
with open('filename') as f:
print f.read()
5.程序示例:
*******示例
1)
import time
def timmer(func):
def dec():
start_time = time.time()
func()
stop_time = time.time()
# return "%s run %fs"%(func.__name__,stop_time-start_time)
log=open('log','a+')
log.write("%s run %f s\n"%(func.__name__,stop_time-start_time))
log.close()
return "%s run %f s \n"%(func.__name__,stop_time-start_time)
return dec
@timmer #hello1 =timmer(hello1)
def hello1():
print 'hello1...'
time.sleep(1)
@timmer ##hello2 =timmer(hello2)
def hello2():
print 'hello2...'
time.sleep(2)
print hello1()
print hello2(