-1

Novice level Python learner and working on macos Catalina with newly downloaded Python 3.8 installation, using Jupyter Notebook.

readlines() is returning all one line with \n, separators instead of individual lines.

foo = open('foo.txt')
foo.seek(0)
foo.readlines()

Returns:

['Something on line 1.\n', 'Something on line 2.\n', 'Something on line 3.']

The foo.txt file looks like this:

Something on line 1.
Something on line 2.
Something on line 3.

Am I right in thinking this is not expected behaviour? I can't find a similar query here. Thank you.

Edit - this is how it appears in Jupyter Notebook on the tutorial. Perhaps that is a Notebook setting?

image

Red
  • 26,798
  • 7
  • 36
  • 58
sadkate
  • 3
  • 4
  • The output is not 'one line with \n separators', it's a list of 3 strings, each being one of your lines. Mind the quotes. – Thierry Lathuille Jun 04 '20 at 21:28
  • The output in your picture is exactly the same as in your text: a list of 3 lines. Jupyter tries to print lists in a 'prettier' way than the REPL does by printing list items one by line', that's all. – Thierry Lathuille Jun 04 '20 at 21:34

1 Answers1

0

Am I right in thinking this is not expected behaviour?

No, that's what's supposed to happen in any python editor.

readlines() is returning all one line with \n, separators instead of individual lines.

If you want multiple lines, just do this:

foo = open('foo.txt')
foo.seek(0)
foo.read()
Red
  • 26,798
  • 7
  • 36
  • 58
  • Ah now I see it *is* a list. I was confused because it appeared on one line while the tutorial guy's list was separated by carriage returns. I'm not sure why that is. I will put a pic in the question. – sadkate Jun 04 '20 at 21:28