Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file.write creating extra carriage return

Tags:

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?

like image 240
Chris Avatar asked Oct 26 '10 16:10

Chris


People also ask

Does Python write add a new line?

In Python, the new line character ā€œ\nā€ is used to create a new line.

How do you write Crlf in Python?

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.

What does write () returns in Python?

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.

How do you create a new line in a text file in Python?

šŸ”¹ 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.


2 Answers

\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.

like image 121
adw Avatar answered Sep 22 '22 18:09

adw


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.

like image 30
Daniele Bacarella Avatar answered Sep 21 '22 18:09

Daniele Bacarella