user741186
user741186

Reputation: 1

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?

Upvotes: 0

Views: 2297

Answers (3)

Alan
Alan

Reputation: 376

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") 

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318518

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.

Upvotes: 2

Joachim Sauer
Joachim Sauer

Reputation: 308041

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

open('seq_fasta.txt')

Upvotes: 8

Related Questions