2012-07-15 46 views
-2

所以我的問題是,當它的一個在服務器中找不到文件時,我的代碼會崩潰。有沒有辦法跳過找不到文件的過程,並在循環中繼續。 這裏是我下面的代碼:如何在服務器上找不到文件時停止代碼崩潰?

fname = '/Volumes/database/interpro/data/'+uniprotID+'.txt'

for index, (start, end) in enumerate(searchPFAM(fname)): 
     with open('output_'+uniprotID+'-%s.txt' % index,'w') as fileinput: 
      print start, end 
      for item in lookup[uniprotID]: 
       item, start, end = map(int, (item, start, end)) #make sure that all value is int 
       if start <= item <= end: 
        print item 
        result = str(item - start) 
        fileinput.write(">{0} | at position {1} \n".format(uniprotID, result)) 
        fileinput.write(''.join(makeList[start-1:end])) 
        break 
      else: 
        fileinput.write(">{0} | N/A\n".format(uniprotID)) 
        fileinput.write(''.join(makeList[start-1:end])) 

回答

11

你需要使用try/except塊來處理異常。請參閱handling exceptions的Python文檔。

在這種情況下,你必須包裹open()調用(一切都在那with塊),與try,並趕上與except IOError例外:

for ... 
    try: 
     with open(... 
      # do stuff 
    except IOError: 
     # what to do if file not found, or pass 

其他信息

你真正應該做的,就是將那個外部的for循環變成一個函數。或者可能是with的主體,轉換爲處理打開文件的函數。無論哪種方式,減少嵌套使事情變得更加可讀,並且更容易進行這種更改,並添加try/except

實際上,您似乎在外部for循環的每次迭代中重新打開文件,但文件名永遠不會更改 - 您總是重新打開同一個文件。那是故意的嗎?如果沒有,你可能想重新考慮你的邏輯,並將其移到循環之外。

第三個想法是,你得到的例外是什麼?它是一個文件未找到IOError?因爲你正在打開文件('w'),所以我不確定爲什麼你會得到這個異常。

+0

我不明白你打包open()調用(以及與塊的一切)? – 2012-07-15 23:05:18

+0

我做了一個編輯以包含代碼。 – 2012-07-15 23:10:40

+0

該操作系統我得到了IOError:找不到文件 – 2012-07-15 23:26:41

1
for index, (start, end) in enumerate(searchPFAM(fname)): 
    try: 
     newname = 'output_'+uniprotID+'-%s.txt' % index 
     with open(newname,'w') as fileinput: 
      print start, end 
      for item in lookup[uniprotID]: 
       item, start, end = map(int, (item, start, end)) #make sure that all value is int 
       if start <= item <= end: 
        print item 
        result = str(item - start) 
        fileinput.write(">{0} | at position {1} \n".format(uniprotID, result)) 
        fileinput.write(''.join(makeList[start-1:end])) 
        break 
       else: 
        fileinput.write(">{0} | N/A\n".format(uniprotID)) 
        fileinput.write(''.join(makeList[start-1:end])) 
    except IOError: 
     print 'Couldn't find file %s' % newname 
相關問題