Fred Zimmerman
Fred Zimmerman

Reputation: 1238

NameError: name 'file' is not defined

This works in Python 2.7 but not in 3.5.

def file_read(self, input_text):

    doc = (file.read(file(input_text))).decode('utf-8', 'replace')

I'm trying to open this file, input_text is a path value from argparse.

I get this error.

NameError: name 'file' is not defined

I gather that Python 3.5 uses "open" instead of "file", but I don't quite get how to use open in a situation like this.

Upvotes: 2

Views: 19880

Answers (1)

Your original code works in Python 2.7 but it is bad style there. The file for this use was deprecated long time ago in favour of using open, and instead of calling the file.read passing the file as the argument you should have just called the .read method on the returned object.

The correct way to write the code you did on Python 2 would have been

with open(input_text) as docfile:
     doc = docfile.read().decode('utf-8', 'replace')

This does not work as such in Python 3, because open without mode would now default to reading unicode text. Furthermore it would assume the file is in native encoding and decode it with strict error handling. However, Python 3 actually makes working with text files easier than in Python 2, as you can pass the encoding and errors behaviour as arguments to open itself:

with open(input_text, encoding='utf-8', errors='replace') as docfile:
     doc = docfile.read()

Upvotes: 4

Related Questions