20

I am trying to output the result from a Python script to a text file where each output should be saved to a line.

f1=open('./output.txt', 'a')
f1.write(content + "\n")

When I open output.txt with the regular notepad the results look like this:

color amber color aqua color analysis color app color adobe color alive app

However, when I open the file with notepad++ it looks fine and each word is saved on a line.

How can make the script save the result line-by-line so it would show the same on the regular notepad?

bastelflp
  • 9,362
  • 7
  • 32
  • 67
user2334436
  • 949
  • 5
  • 13
  • 34
  • 2
    see http://www.cs.toronto.edu/~krueger/csc209h/tut/line-endings.html you should use '\r\n' on Windows – Paweł Kordowski Feb 28 '16 at 17:06
  • What installation of python are you using? – AChampion Feb 28 '16 at 18:06
  • Can you display the ending characters inside Notepad++ so that we can see what is happening? (see [here](http://stackoverflow.com/a/1446382/1559401) on how to enable that feature) – rbaleksandar Feb 28 '16 at 23:02
  • If the python documentation were written properly you would not need to ask this question. It's not your fault however, its the poor python documentation. – Andrew S Nov 01 '16 at 04:07

2 Answers2

22

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • 30
    I voted this down because of the [official documentation](https://docs.python.org/2/library/os.html#os.linesep) on `os.linesep` – rbaleksandar Feb 28 '16 at 17:18
  • 5
    Good point, but then the OP shouldn't have an issue but they are, suggesting to write `'\r\n'` is what I was responding to - using `os.linesep` is more portable. – AChampion Feb 28 '16 at 18:02
  • 3
    The best solution! It's better than f1.write(content + "\n") – SergeyYu Nov 28 '18 at 09:25
  • 1
    Do we absolutely need to `import os`? – Samuel Nde Dec 14 '18 at 18:28
  • 1
    @NdeSamuelMbah if you want to use `os.linesep` - you do. – AChampion Dec 15 '18 at 02:53
  • 2
    Normally when using `f1.write(content + "\n")`, python automatically convert the `"\n"` to `os.linesep` (https://stackoverflow.com/questions/38074811/what-is-os-linesep-for). The problem should elsewhere... – Jean Paul May 27 '19 at 16:10
17

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

bastelflp
  • 9,362
  • 7
  • 32
  • 67
Peter Badida
  • 11,310
  • 10
  • 44
  • 90