-2

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
  • 1
    `some_file.txt` as identifier -- ? – RomanPerekhrest Jul 21 '19 at 16:17
  • `print(some_string)` will also fail since `some_string` is not defined. – FObersteiner Jul 21 '19 at 16:19
  • @RomanPerekhrest: `some_file` is the identifier and `some_file.txt` is the file to be opened –  Jul 21 '19 at 16:26
  • Possible duplicate of [open() in Python does not create a file if it doesn't exist](https://stackoverflow.com/questions/2967194/open-in-python-does-not-create-a-file-if-it-doesnt-exist) – gregory Jul 21 '19 at 16:27
  • @david, well, that's wrong attempt – RomanPerekhrest Jul 21 '19 at 16:28
  • I forgot the quotation marks around `some_file.txt` (see answer). Or is there something else wrong? –  Jul 21 '19 at 16:29
  • @gregory: [open() in Python does not create a file if it doesn't exist](https://stackoverflow.com/questions/2967194/open-in-python-does-not-create-a-file-if-it-doesnt-exist) deals with a different issue –  Jul 21 '19 at 16:32
  • @david there are bunch of examples showing quotes around the file one wishes to open to read or write in the topic I cited. Proper basic syntax is better covered there. This question should be closed. – gregory Jul 21 '19 at 16:43

2 Answers2

1

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

Replace some_file.txt with 'some_file.txt'

Prof
  • 637
  • 13
  • 24
  • Quick follow-up question. Let `some_file.txt` contain five lines of text: first second third fourth fifth The above code gives: ['f', 'i', 'r', 's', 't', '\n', 's', 'e', 'c', 'o', 'n', 'd', '\n', 't', 'h', 'i', 'r', 'd', '\n', 'f', 'o', 'u', 'r', 't', 'h', '\n', 'f', 'i', 'f', 't', 'h'] What I need instead: ['first', 'second', 'third', 'fourth', 'fifth'] Why does `read()` split words into symbols and why does `rstrip('\n')` have no effect? –  Jul 21 '19 at 17:01
0

All questions are answered here:

When should I ever use file.read() or file.readlines()?

Topic can be closed.