Avoid writing carriage return when writing line feed with Python -
if taken consideration carriage return = \r
, line feed = \n
python 3.5.1 (v3.5.1:37a07cee5969, dec 6 2015, 01:38:48) [msc v.1900 32 bit (intel)] on win32 type "help", "copyright", "credits" or "license" more information. >>> '{:02x}'.format(ord('\n')) '0a' >>> '{:02x}'.format(ord('\r')) '0d'
how avoid writing carriage return when using open('filename','w').write('text\n')
?
in interactive mode can this:
>>> open('filename','w').write('text\n') 5 >>> c in open('filename','r').read(): ... print('{:02x}'.format(ord(c))) ... 74 65 78 74 0a
this indicate line feed has been written, should 5 bytes long.
-rw-r--r-- 1 djuric 197121 6 jul 15 21:00 filename ^
it 6 bytes long. can "windows thing", when open file in notepad++ example, , turn view > show symbols > show characters can see carriage return there.
after pressing ctrl+h , replacing \r nothing using extended search mode, line feed left. after saving file, line feed in file , file 5 bytes long.
-rw-r--r-- 1 djuric 197121 5 jul 15 20:58 filename1 ^
so why notepad++ able save line feeds without carriage return, python can't?
you can passing ''
newline
parameter when opening text file.
f = open('test.txt', 'w', newline='') f.write('only lf\n') f.write('cr + lf\r\n') f.write('only cr\r') f.write('nothing') f.close()
as described in docs:
newline controls how universal newlines mode works (it applies text mode). can none, '', '\n', '\r', , '\r\n'. works follows:
when reading input stream, if newline none, universal newlines mode enabled. lines in input can end in '\n', '\r', or '\r\n', , these translated '\n' before being returned caller. if '', universal newlines mode enabled, line endings returned caller untranslated. if has of other legal values, input lines terminated given string, , line ending returned caller untranslated.
when writing output stream, if newline none, '\n' characters written translated system default line separator, os.linesep. if newline '' or '\n', no translation takes place. if newline of other legal values, '\n' characters written translated given string.
the default value newline
none
, specifiying ''
, you're forcing python write newline (\n
or \r
) without translating it.
Comments
Post a Comment