Can't open file: "NameError: name <filename> is not defined"
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?
You need to specify the file name as a string literal:
open('seq_fasta.txt')
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.
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")
精彩评论