python with as 进行文件读取

来源:互联网 发布:淘宝注册流程图 编辑:程序博客网 时间:2024/06/08 16:58

1. 用with...as...来做文件内容的读取(在内容不多的情况下,如果文件巨大,还是一行一行读取吧)

filename = os.path.join(self._data_path, 'Annotations', index + '.txt'with open(filename) as f:    lines = [x.strip() for x in f.readlines() if string.atoi(x.strip().split()[2]) > 3]

这样两行语句就可以完成读写工作,简介明了。 并且with...as...语句内置了__enter__ 和__exit__操作,会自动关闭file,所以不用显示调用:

f.close()


0 0
原创粉丝点击