python -文件操作





###############################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(


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值