2

I wrote python code to write to a file like this:

   with codecs.open("wrtieToThisFile.txt",'w','utf-8') as outputFile:
            for k,v in list1:
                outputFile.write(k + "\n")

The list1 is of type (char,int) The problem here is that when I execute this, file doesn't get separated by "\n" as expected. Any idea what is the problem here ? I think it is because of the

with

Any help is appreciated. Thanks in advance. (I am using Python 3.4 with "Python Tools for Visual Studio" version 2.2)

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Indish Cholleti
  • 887
  • 3
  • 11
  • 21

4 Answers4

10

If you are on windows the \n doesn't terminate a line.
Honestly, I'm surprised you are having a problem, by default any file opened in text mode would automatically convert the \n to os.linesep. I have no idea what codecs.open() is but it must be opening the file in binary mode.
Given that is the case you need to explicitly add os.linesep:

outputFile.write(k + os.linesep)

Obviously you have to import os somewhere.

AChampion
  • 29,683
  • 4
  • 59
  • 75
3

Figured it out, from here:

How would I specify a new line in Python?

I had to use "\r\n" as in Windows, "\r\n" will work.

Community
  • 1
  • 1
Indish Cholleti
  • 887
  • 3
  • 11
  • 21
  • 3
    Not very portable, use `os.linesep`, which will put the right line separator for whatever system you are on. – AChampion Sep 18 '15 at 23:58
  • Thanks, but I tried it and it just prints os.linesep where I wanted the new line break. I am writing to a text file in windows. Even I want something portable. – Indish Cholleti Sep 19 '15 at 00:00
3

Per codecs.open's documentation, codecs.open opens the underlying file in binary mode, without line ending conversion. Frankly, codecs.open is semi-deprecated; in Python 2.7 and onwards, io.open (which is the same thing as the builtin open function in Python 3.x) handles 99% of the cases people used to use codecs.open, but better (faster, and without stupid issues like line endings). If you're reliably running on Python 3, just use plain open; if you need to run on Python 2.7 as well, import io and use io.open.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • I didn't just use codecs.open simply, it was for other requirement which otherwise won't decode my required file – Indish Cholleti Sep 19 '15 at 02:46
  • Unless your file was in one of the pseudocodecs (`hex`, `rot13` and the like), `io.open` should handle it. It reads and writes non-ASCII-encoded files just fine; it's not Py2's default `open` where it would only read `str`, not `unicode`. – ShadowRanger Sep 19 '15 at 15:29
0

If you are on windows, try '\r\n'. Or open it with an editor that recognizes unix style new lines.

multivac
  • 146
  • 5