【问题标题】:try: and exception: error尝试:和异常:错误
【发布时间】:2012-07-10 16:07:22
【问题描述】:

所以我正在处理下面的代码。当我的 Reff.txt 有不止一行时,它符合要求。但是当我的 Reff.txt 文件只有一行时它不起作用。这是为什么?我还想知道为什么我的代码不运行我的代码的“尝试”部分,但它总是只运行“异常”部分。

  • 所以我有一个参考文件,其中包含一个 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()

【问题讨论】:

  • 你的 with 块是怎么回事?它立即通过...
  • 把它从 try except 块中取出,看看你得到了什么错误......猜测文件不存在
  • 为什么每个区块后面都有一个无条件的break
  • 另外,filename = open( 有点误导,因为它不是名称,它是一个对象,您可以直接使用 etree.parse('filename') 而无需显式打开句柄
  • 如果您解释一下您所拥有的以及您想要实现的目标(可能是要点),这可能会有所帮助 - 我正在努力遵循代码和您的意图......跨度>

标签: python exception try-catch


【解决方案1】:

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

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

ETA:另外,您似乎只对测试 for 循环的第一遍感兴趣?你在那个时候打破。在这种情况下,您的其他休息时间是无关紧要的,因为当那个休息时间在那里时,它们永远不会到达。

【讨论】:

  • 我正在尝试检查是否存在“dbname =pfam”。如果没有,那么我不想创建输出文件。但我不确定最好的方法是什么。
  • 在使用它之前,您必须在某个时候声明 outputFile 对象。当您进入 FOR 循环时,您已经知道 dbname=pfram 是真的,对吧?所以只要把“outputFile = open(#whatever)”放在你声明开始和结束的地方,你知道吗?
猜你喜欢
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多