2012-07-15 49 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 
相关问题