Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法打开文件:“名称错误:未定义名称”_Python_File Io - Fatal编程技术网

Python 无法打开文件:“名称错误:未定义名称”

Python 无法打开文件:“名称错误:未定义名称”,python,file-io,Python,File Io,我正在创建一个程序来读取FASTA文件,并在某些特定字符(如“>”等)处拆分。但我面临一个问题 计划部分为: >>> def read_FASTA_strings(seq_fasta): ... with open(seq_fasta.txt) as file: ... return file.read().split('>') 错误: Traceback (most recent call last): File "<st

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


除此之外,您可以选择不同的名称,但文件使用此名称会隐藏一个内置名称。

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

这是行不通的,因为seq_fasta.txt实际上没有指向任何东西,因此您的错误。您需要做的是在“seq_fasta.txt”周围加上引号,或者创建一个包含该变量的文本字符串对象,并在open函数中使用该变量名。由于.txt文件,它认为函数头中的seq_fastain和函数体中的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") 

我想,“seq_fasta.txt”应该用引号括起来。确保你没有重新发明轮子:是的..谢谢你的建议和努力: