繁体   English   中英

无法打开文件:“NameError: name<filename> 没有定义”

[英]Can't open file: "NameError: name <filename> is not defined"

我正在创建一个程序来读取 FASTA 文件并在某些特定字符处拆分,例如“ > ”等。但我遇到了一个问题。

程序部分是:

>>> def read_FASTA_strings(seq_fasta):
...     with open(seq_fasta.txt) as file: 
...             return file.read().split('>') 

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'seq_fasta' is not defined

如何摆脱这个问题?

您需要将文件名指定为字符串文字:

open('seq_fasta.txt')

您需要引用文件名: open('seq_fasta.txt')

除此之外,您可以选择不同的名称,但file因为使用此名称会掩盖内置名称。

您的程序将 seq_fasta.txt 视为对象标签,类似于您在导入 math 模块后使用 math.pi 的方式。

这是行不通的,因为 seq_fasta.txt 实际上没有指向任何内容,因此您的错误。 您需要做的是在“seq_fasta.txt”周围加上引号,或者创建一个包含该对象的文本字符串对象,并在 open 函数中使用该变量名。 由于 .txt 它认为 seq_fasta(在函数头中)和 seq_fasta.txt(在函数体中)是两个不同的标签。

接下来,你不应该使用文件,因为它是 python 的一个重要关键字,你最终可能会遇到一些棘手的错误和坏习惯。

def read_FASTA_strings(somefile):
    with open(somefile) as textf: 
        return textf.read().split('>')

然后使用它

lines = read_FASTA_strings("seq_fasta.txt") 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM