Python shell在读取(fasta)文件时冻结

时间:2012-03-05 21:37:37

标签: python shell freeze fasta

我将首先展示我到目前为止的代码:

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

1 个答案:

答案 0 :(得分:1)

您没有定义e 所以你会得到一个被裸except:隐藏的NameError。

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

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

在像你这样的情况下,当你不一定知道异常是什么时,你应该至少使用this method of displaying information about the error

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在linux2上使用Python 3.2.2 [GCC 4.6.1]。

一些建议:

  • 从小处开始。得到一个简单的工作,然后添加一个步骤。
  • 在问题点添加print()语句。

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