您的位置:首页 > 编程语言 > Python开发

Python使用with时本猿犯了一个错误

2016-11-01 22:06 281 查看
以下这段代码导致压缩包内的图片不完整,重新解压后发现文件大小比原文件小一点点。

但是导致图片无法打开,我也是由图片打不开这个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()


这样写就一点问题都没有。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐