如果目录中没有文件,如何跳过?

时间:2018-08-08 14:31:27

标签: python

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

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)

enter image description here

那么确保我得到期望结果的最佳方法是什么。

3 个答案:

答案 0 :(得分:2)

要测试目录中是否存在4个文件,您可以执行以下操作:

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

答案 1 :(得分:0)

您可以这样做:

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

它将返回False或True。

答案 2 :(得分:-1)

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