1

我将首先展示我目前拥有的代码:

def err(em):
    print(em)
    exit

def rF(f):
    s = ""
    try:
        fh = open(f, 'r')
    except IOError:
        e = "Could not open the file: " + f
        err(e)

    try:
        with fh as ff:
            next(ff)
            for l in ff:
                if ">" in l:
                    next(ff)
                else:
                    s += l.replace('\n','').replace('\t','').replace('\r','')
    except:
        e = "Unknown Exception"
        err(e)
    fh.close()
    return s

出于某种原因,每当我尝试通过键入以下内容读取文件时,python shell(我使用的是 3.2.2)都会冻结:

rF("mycobacterium_bovis.fasta")

rF 函数中的条件是防止读取以“>”标记开头的每一行。这些行不是 DNA/RNA 代码(这是我试图从这些文件中读取的),应该被忽略

我希望任何人都可以帮助我解决这个问题,我没有看到我的错误。

像往常一样,提前非常感谢!

编辑: *问题仍然存在!* 这是我现在使用的代码,我删除了无论如何都是一个花哨的添加的错误处理,当尝试读取文件时,shell 仍然冻结。这是我现在的代码:

def rF(f):
    s = ""
      try:
          fh = open(f, 'r')
    except IOError:
        print("Err")

    try:
        with fh as ff:
            next(ff)
            for l in ff:
                if ">" in l:
                    next(ff)
                else:
                    s += l.replace('\n','').replace('\t','').replace('\r','')
    except:
        print("Err")

    fh.close()
    return s
4

1 回答 1

1

你从来没有定义e.
所以你会得到一个 NameError 被裸隐藏的错误except:

这就是为什么指定异常是好的和健康的,例如:

try: 
    print(e)
except NameError as e: 
    print(e)

但是,在像您这样的情况下,当您不一定知道异常是什么时,您至少应该使用这种显示有关错误信息的方法

import sys
try:
    print(e)
except: # catch *all* exceptions
    e = sys.exc_info()[1]
    print(e)

其中,使用您发布的原始代码,将打印以下内容:

name 'e' is not defined

根据更新的信息进行编辑:
如果文件很大,连接这样的字符串会很慢。
考虑改为将过滤后的信息写入另一个文件,例如:

def rF(f):
  with open(f,'r') as fin, open('outfile','w') as fou:
    next(fin)
    for l in fin:
      if ">" in l:
        next(fin)
      else:
        fou.write(l.replace('\n','').replace('\t','').replace('\r',''))

我已经根据此处列出的格式规范测试了上述代码适用于 FASTA 文件:http ://en.wikipedia.org/wiki/FASTA_format using Python 3.2.2 [GCC 4.6.1] on linux2。

几个建议:

  • 从小处着手。让一个简单的作品工作,然后添加一个步骤。
  • print()在麻烦点 添加语句。

此外,请考虑包含有关您尝试解析的文件内容的更多信息。这可能使我们更容易提供帮助。

于 2012-03-05T21:47:06.413 回答