try: and exception: error



所以我正在处理下面的代码。当我的Reff.txt有多行时,它运行良好。但当我的Reff.txt文件只有一行时,它就不起作用了。为什么?我还想知道为什么我的代码不运行代码的"try"部分,而总是只运行"exception"部分。

  • 所以我有一个引用文件,它有一个id列表(每行一个id)
  • 我使用参考文件(Reff.txt)作为参考,从网站上搜索数据库,从网络中的服务器上搜索数据库
  • 我应该得到的结果是应该有一个输出文件和带有该id信息的文件;对于每个引用id

然而,这个代码对我的"try:"部分根本没有任何作用

import sys
import urllib2
from lxml import etree
import os
getReference = open('Reff.txt','r') #open the file that contains list of reference ids
global tID 
for tID in getReference:    
    tID = tID.strip()
    try:
        with open(''+tID.strip()+'.txt') as f: pass
        fileInput = open(''+tID+'.txt','r')
        readAA = fileInput.read()
        store_value = (readAA.partition('n'))
        aaSequence = store_value[2].replace('n', '') #concatenate lines
        makeList = list(aaSequence)#print makeList
        inRange = ''
        fileAddress = '/database/int/data/'+tID+'.txt'
        filename = open(fileAddress,'r')#name of the working file
        print fileAddress
        with open(fileAddress,'rb') as f:
            root = etree.parse(f)
            for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn"):#find dbname =PFAM
                start = int(lcn.get("start"))#if it is PFAM then look for start value
                end = int(lcn.get("end"))#if it is PFAM then also look for end value
                while start <= end:
                    inRange = makeList[start]
                    start += 1
                    print outputFile.write(inRange) 
                    outputFile.close()
                break
            break
        break
    except IOError as e:

        newURL ='http://www.uniprot.org/uniprot/'+tID+'.fasta'
        print newURL
        response = urllib2.urlopen(''+newURL) #go to the website and grab the information 
        creatNew = open(''+uniprotID+'.txt','w')
        html = response.read() #read file
        creatNew.write(html) 
        creatNew.close()

因此,当您执行Try/Except时-如果尝试失败,则运行Except。除外总是在运行,因为尝试总是失败。

最可能的原因是您有这个-"print outputFile.write(inRange)",但您之前没有声明outputFile。

ETA:而且,看起来你只对测试for循环的第一次通过感兴趣?你在那一点上崩溃了。在这种情况下,你的其他休息时间是无关的,因为当那个休息时间在那里的时候,它们永远不会到达。

相关内容

最新更新