I'm writing a series of SQL statements to a file using python. The template string looks like:
store_insert = '\tinsert stores (storenum, ...) values (\'%s\', ...)'
I'm writing to the file like so:
for line in source: line = line.rstrip() fields = line.split('\t') script.write(store_insert % tuple(fields)) script.write(os.linesep)
However, in the resulting output, I see \r\r\n at the end of each line, rather than \r\n as I would expect. Why?
In Python, the new line character ā\nā is used to create a new line.
In Python, a carriage return is represented by the string \r and a newline character is represented by the string \n. The backslash is an escape character that tells Python that the following character has a special meaning. To type an actual backslash, put a second backslash before it to have Python escape it as well.
Python File write() MethodThere is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.
š¹ In Summary The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.
\n
is converted to os.linesep
for files opened in text-mode. So when you write os.linesep
to a text-mode file on Windows, you write \r\n
, and the \n
gets converted resulting in \r\r\n
.
See also the docs:
Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.
With Python 3
open()
introduces the new parameter newline
that allows to specify a string which any occurrence of \n
will be translated to.
Passing an empty string argument newline=''
disables the translation, leaving the new line char as it is. Valid for text mode only.
From the documentation
On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With