Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "\n" while writing to files [duplicate]

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)

like image 226
Indish Cholleti Avatar asked Dec 03 '25 17:12

Indish Cholleti


2 Answers

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.

like image 71
AChampion Avatar answered Dec 06 '25 08:12

AChampion


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.

like image 42
Indish Cholleti Avatar answered Dec 06 '25 07:12

Indish Cholleti