无法打开文件。"NameError: name <filename> is not defined" (错误:名称<文件名>未定义)

问题描述 投票:0回答:3

我正在创建一个程序来读取一个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

如何解决这个问题?

python file-io
3个回答
7
投票

你需要将文件名指定为一个字符串文字。

open('seq_fasta.txt')

2
投票

你需要引用文件名。open('seq_fasta.txt').

除此之外,你可能会选择一个不同的名字,但是......。file 因为使用这个名字会影响到一个内置的名字。


1
投票

你的程序将seq_fasta.txt看作是一个对象标签,类似于导入数学模块后使用math.pi的方式。

这是不可能的,因为seq_fasta.txt实际上并不指向任何东西,因此你的错误。你需要做的是在'seq_fasta.txt'周围加上引号,或者创建一个包含该文本字符串的对象,并在打开函数时使用该变量名。因为.txt,它认为seq_fasta(在函数头)和seq_fasta.txt(在函数体)是两个不同的标签。

其次,你不应该使用file,因为它是python的一个重要关键字,你可能最终会出现一些棘手的bug和坏习惯。

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

然后使用它

lines = read_FASTA_strings("seq_fasta.txt") 
© www.soinside.com 2019 - 2024. All rights reserved.