Search code examples
pythonfile-ionameerror

Why does using open(filename) fail with "'filename' is not defined"?


I want to open a text file containing a column of words and create a list or, alternatively, a string containing these words.

Why do I get this error:

>>> with open(some_file.txt, 'r') as some_file:
...    some_list = [_ for _ in some_file.read().rstrip('\n')]
...    print(some_list)

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

Solution

  • Python is looking for an object called some_file instead of a path string.

    Replace some_file.txt with 'some_file.txt'