python的文件操作用得越来越多了,常常还是想不起来需要搜索。写博客记录一下,也帮助记忆。主要是读写。
- 打开使用try, 关闭finally,捕捉异常except as;或者使用简单的方法with as,可以合并前两个语句,但是无法捕捉异常。
- open(), close(),或者 with open() as
- open(文件路径, 操作),下面操作内容转自http://www.cnblogs.com/feeland/p/4477535.html
- file一些方法:file.read file.write filr.tell()告诉位置 file.readline file writelines
- 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()