Can't open file: “NameError: name <filename> is not defined”

元气小坏坏 提交于 2020-06-18 11:27:17

问题


I am creating a program to read a FASTA file and split at some specifc characters such as '>' etc. But I'm facing a problem.

The program part is:

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

The error:

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

How to get rid of this problem?


回答1:


You need to specify the file name as a string literal:

open('seq_fasta.txt')



回答2:


You need to quote the filename: open('seq_fasta.txt').

Besides that, you might choose a different name but file as using this name shadows a builtin name.




回答3:


Your program is seeing seq_fasta.txt as a object label, similar to how you would use math.pi after importing the math module.

This is not going to work because seq_fasta.txt doesnt actually point to anything, thus your error. What you need to do is either put quotes around it 'seq_fasta.txt' or create a text string object containing that and use that variable name in the open function. Because of the .txt it thinks seq_fasta(in the function header) and seq_fasta.txt(in the function body) are two different labels.

Next, you shouldnt use file as it is an important keyword for python and you could end up with some tricky bugs and a bad habit.

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

and then to use it

lines = read_FASTA_strings("seq_fasta.txt") 


来源:https://stackoverflow.com/questions/5908067/cant-open-file-nameerror-name-filename-is-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!