忽略for循环中丢失的文件 – Python
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了忽略for循环中丢失的文件 – Python,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1908字,纯文字阅读大概需要3分钟。
内容图文
![忽略for循环中丢失的文件 – Python](/upload/InfoBanner/zyjiaocheng/744/df3fcc229827444f899082b3324cb825.jpg)
我正在浏览一些文件,并在我的代码中划分它们的值. for循环用于解析文件类型的多次迭代(它只是更快).但是,有时,文件可能不存在.我如何跳过它并让for循环继续,因为某些文件编号可能因某种原因而不存在.
码:
import pyfits as pf
for i in range (1,18):
img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits")
img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits")
img3=(img2)[2]
newimg=img1/img3
pf.writeto("dividedsciPHOTOf105w"+str(i)+".fits",newimg, clobber=True)
for i in range (1,18):
img1= pf.getdata("galmasksciPHOTOf125w"+str(i)+".fits")
img2= pf.getdata("fittedsciPHOTOf125w"+str(i)+".fits")
img3=(img2)[2]
newimg=img1/img3
pf.writeto("dividedsciPHOTOf125w"+str(i)+".fits",newimg, clobber=True)
for i in range (1,22):
img1= pf.getdata("galmasksciPHOTOf140w"+str(i)+".fits")
img2= pf.getdata("fittedsciPHOTOf140w"+str(i)+".fits")
img3=(img2)[2]
newimg=img1/img3
pf.writeto("dividedsciPHOTOf140w"+str(i)+".fits",newimg, clobber=True)
for i in range (1,22):
img1= pf.getdata("galmasksciPHOTOf160w"+str(i)+".fits")
img2= pf.getdata("fittedsciPHOTOf160w"+str(i)+".fits")
img3=(img2)[2]
newimg=img1/img3
pf.writeto("dividedsciPHOTOf160w"+str(i)+".fits",newimg, clobber=True)
因此,例如,fitssciPHOTOf125w4不存在,Python停止那里的代码.
解决方法:
您可以使用os.path.exists或os.path.isfile来首先测试文件是否存在.或者把你的阅读陈述试试……除了:传递阻止.
for i in range (1,18):
if os.path.isfile("galmasksciPHOTOf105w"+str(i)+".fits") and os.path.exists("fittedsciPHOTOf105w"+str(i)+".fits"):
img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits")
img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits")
img3=(img2)[2]
newimg=img1/img3
pf.writeto("dividedsciPHOTOf105w"+str(i)+".fits",newimg, clobber=True)
要么:
for i in range (1,18):
try:
img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits")
img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits")
img3=(img2)[2]
newimg=img1/img3
pf.writeto("dividedsciPHOTOf105w"+str(i)+".fits",newimg, clobber=True)
except IOError:
pass
内容总结
以上是互联网集市为您收集整理的忽略for循环中丢失的文件 – Python全部内容,希望文章能够帮你解决忽略for循环中丢失的文件 – Python所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。