2.22python基础(3) 文件操作

python的文件操作用得越来越多了,常常还是想不起来需要搜索。写博客记录一下,也帮助记忆。主要是读写。

  1. 打开使用try, 关闭finally,捕捉异常except as;或者使用简单的方法with as,可以合并前两个语句,但是无法捕捉异常。
  2. open(), close(),或者 with open() as
  3. open(文件路径, 操作),下面操作内容转自http://www.cnblogs.com/feeland/p/4477535.html
  4. file一些方法:file.read file.write filr.tell()告诉位置 file.readline file writelines
  5. str.replace()

‘Hello Joshua’.replace(‘Hello’, ‘lalala’)
‘lalala Joshua’

一个例子:

 try:
    file = open(path, "w") 
    file.write("Hello Joshua")
except errors.DfpReportError as e:
    print('Failed to generate report. Error was: %s' % e)      
finally:
    file.close()

猜你喜欢

转载自blog.csdn.net/joshuajinxiaoshuai/article/details/79350382