【问题标题】:How to skip a file if it's not there in the directory?如果目录中没有文件,如何跳过该文件?
【发布时间】:2019-01-15 20:54:40
【问题描述】:

所以我在这里阅读适合文件。

path = "/home/Desktop/2d_spectra"
for filename in os.listdir(path):
   if filename.endswith("_e2ds_A.fits"):
      e2ds_hdu = fits.open(filename)
      e2ds_header = e2ds_hdu[0].header
      blaze_file = e2ds_header['HIERARCH ESO DRS BLAZE FILE']
      date = e2ds_header['DATE-OBS']
      date2 = date = date[0:19]
      bis_file = glob('HARPS.' + date2 + '*_bis_G2_A.fits')
      ccf_table = glob('HARPS.' + date2 + '*_ccf_G2_A.tbl')
      filenames = {'filename', 'blaze_file', 'bis_file', 'ccf_table'}
      all_exist = filenames.issubset(os.listdir(path))

现在我想确保我的脚本仅在上面定义的所有四个文件(文件名、blaze_file、bis_file、ccf_table)都在目录中时才执行下一部分计算,因为某些文件不在文件夹,因此它给出了错误:“没有这样的文件或目录”。

      blaze_hdu = fits.open(blaze_file)
      blaze = blaze_hdu[0].data
      data_cor = data/blaze

      bis_hdu = fits.open(bis_file[0])
      bis_header = bis_hdu[0].header
      berv = bis_header['HIERARCH ESO DRS BERV']                         
      rv   = bis_header['HIERARCH ESO DRS CCF RV']
      rvn  = bis_header['HIERARCH ESO DRS CCF NOISE']

      df=pd.read_table(ccf_table[0],skiprows=2,usecols=(0,4),names=['order','rv'],)
      df=df.to_dict(orient='dict')

      df = df['rv']
      for i in np.arange(0,72,1):
        ll = wave[i]
        flux = data_cor[i]

      tmpFile = 'order_'+str(i)+'.txt'
      path =  '/home/gyanender/bin/ARES/'+tmpFile
      with open(path, 'w') as f:
         writer = csv.writer(f, delimiter=' ')
         writer.writerows(zip(ll,flux))


      mine_opt =  '/home/gyanender/bin/ARES/mine.opt'
      file_opt=open(mine_opt,'w')
         file_opt.writelines(("specfits='order_"+str(i)+".txt'","\n","readlinedat='linelist.dat'","\n",\
         "fileout='txt_"+str(i)+".ares'","\n","lambdai=3600.","\n","lambdaf=9000.","\n","smoothder=4","\n",\
         "space=3.0","\n","rejt="+str(SN_dic[i][0]),"\n","lineresol=0.1","\n","miniline=1","\n",\
         "plots_flag=0","\n","rvmask='0,0'","\n"))
      file_opt.close()

      working_dir = '/home/gyanender/bin/ARES'               
      subprocess.check_call(['./ARES'], cwd=working_dir)

那么,确保我得到想要的结果的最佳方法是什么。

【问题讨论】:

    标签: python


    【解决方案1】:

    在打开之前使用os.path.exists(path/to/file)

    【讨论】:

    • 他们在目录中列出文件然后检查,无需进行额外检查
    • 文件名来自其他地方。所以需要额外的检查。无论是单独为每个文件这样做还是像 @Jerub 那样做。
    • 他们是通过 listdir 来做的,listdir 不会对现有文件撒谎
    【解决方案2】:

    要测试一个目录中是否存在 4 个文件,您可以这样做:

    filenames = {'filename1.ext', 'filename2.ext', 'filename3.ext', 'filename4.ext'}
    all_exist = filenames.issubset(os.listdir(path))
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      import os.path
      os.path.exists(file_path)
      

      它将返回 False 或 True。

      【讨论】:

        猜你喜欢
        • 2020-01-10
        • 1970-01-01
        • 2023-01-13
        • 2018-10-21
        • 1970-01-01
        • 2012-04-19
        • 2021-12-30
        • 2014-04-08
        • 1970-01-01
        相关资源
        最近更新 更多