【问题标题】:way to stop code from crashing when file not found on the server?在服务器上找不到文件时阻止代码崩溃的方法?
【发布时间】:2012-07-15 22:58:26
【问题描述】:

所以我的问题是,当其中一个无法在服务器中找到文件时,我的代码会崩溃。有没有办法在没有找到文件时跳过查找过程并继续循环。 下面是我的代码:

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]))

【问题讨论】:

    标签: python file loops crash


    【解决方案1】:

    您需要使用 try / except 块来处理异常。请参阅handling exceptions 的 Python 文档。

    在这种情况下,您必须使用try 包装open() 调用(以及该with 块中的所有内容),并使用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'),所以我不确定您为什么会得到该异常。

    【讨论】:

    • 我不明白你所说的包装 open() 调用(以及其中的所有内容)的意思??
    • 我得到的 IOError: file not found
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多