Python使用with时本猿犯了一个错误
2016-11-01 22:06
281 查看
以下这段代码导致压缩包内的图片不完整,重新解压后发现文件大小比原文件小一点点。
但是导致图片无法打开,我也是由图片打不开这个bug一步一步找到是没关流的原因。
这个问题很严重,找了半天才知道是文件流没有关闭导致。
上面这样写是没有关闭流的,因为代码
而只有with语句结束,流才会关闭,这其实和java7的try是一样的。
正确的写法:
这样写就一点问题都没有。
但是导致图片无法打开,我也是由图片打不开这个bug一步一步找到是没关流的原因。
这个问题很严重,找了半天才知道是文件流没有关闭导致。
for d in tableData: imageFile = urllib2.urlopen(d["image"]) img_name=str(partId)+"_"+str(d["id"])+getFilePostfix(d["image"]) img_path=rootDir+img_name with open(img_path, "wb") as f f.write(imageFile.read()) zf.write(img_path, img_name) zf.close()
上面这样写是没有关闭流的,因为代码
zf.write(img_path, img_name)还在with语句块里!!!!
而只有with语句结束,流才会关闭,这其实和java7的try是一样的。
//不需要关流,定义在try的流对象java会自己关 try (FileOutputStream fis=new FileOutputStream(new File("/home/zc/test.py"));FileInputStream fos=new FileInputStream(new File("/home/zc/test.py"))){ fis.write("mytest".getBytes()); fos.read();//这句代码写在这里不一定能读取到“mytest”内容,因为此时fis还没关闭也没有flush刷出。 } catch (Exception e) { e.printStackTrace(); }
正确的写法:
for d in tableData: imageFile = urllib2.urlopen(d["image"]) img_name=str(partId)+"_"+str(d["id"])+getFilePostfix(d["image"]) img_path=rootDir+img_name with open(img_path, "wb") as f f.write(imageFile.read()) zf.write(img_path, img_name) zf.close()
这样写就一点问题都没有。
相关文章推荐
- 使用python-google-places 一个严重的bug 错误提示:lat_lng must be a dict with the keys, 'lat' and 'lng'
- 今天犯了一个很蠢的错误,有关python的模块包的使用的
- Python的print命令使用中的一个小错误
- 今天犯了一个很蠢的错误,有关python的模块包的使用的
- 问题: 在eclipse里使用ctr+shift+t打开一个类的时候,出现错误:Class file name must end with .class
- Python使用pip install psycopg2安装psycopg2包出现python setup.py egg_info failed with error code 1 in /tmp/pip-build-YtLeN3/psycopg2错误处理
- 未知错误 ID:-2147467259 "操作必须使用一个可更新的查询"
- Access中"操作必须使用一个可更新的查询"错误的解决办法
- 错误“操作必须使用一个可更新的查询”原因及解决办法
- 错误“操作必须使用一个可更新的查询”原因及解决办法
- "执行SQL语句时出现问题操作必须使用一个可更新的查询"错误的解决方法
- 一个hash_map使用错误
- 使用STL时的一个链接错误(error LNK2005:std::_Lockit::_Lockit(int)重定义)
- 使用JNDI的一个容易忽略的错误
- 解决 操作必须使用一个可更新的查询"的错误
- 在使用RowDataBound事件时犯的一个错误!
- 在jsp中使用FCKeditor的一个错误
- 错误“操作必须使用一个可更新的查询”原因及解决办法
- 使用makefile和不使用makefile时,容易犯的一个错误。
- 错误提示:操作必须使用一个可更新的查询