加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

忽略for循环中丢失的文件 – Python

发布时间:2020-12-20 11:28:31 所属栏目:Python 来源:网络整理
导读:我正在浏览一些文件,并在我的代码中划分它们的值. for循环用于解析文件类型的多次迭代(它只是更快).但是,有时,文件可能不存在.我如何跳过它并让for循环继续,因为某些文件编号可能因某种原因而不存在. 码: import pyfits as pffor i in range (1,18): img1=
我正在浏览一些文件,并在我的代码中划分它们的值. 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",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",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",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",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",clobber=True)
   except IOError:
       pass

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读