Skip to content Skip to sidebar Skip to footer

Python Inserts Both A Carriage Return And A Line Feed After Variable, Instead Of Just Line Feed

I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc. It works perfectly, however I require only a line feed to be inserted at the end

Solution 1:

For files opened in text mode (the default), python interprets /n as equivalent to os.linesep, which on Windows is [CR][LF], and vice versa.

import osprint(os.linesep)

Check out http://docs.python.org/library/os.html

To prevent this, open the file in binary mode.

withopen("Output.txt", "wb") as my_file: 

This tells Python to treat the file as a plain sequence of bytes and you will find that \n gets treated as a single linefeed character.

Solution 2:

Try:

withopen("Output.txt", "bw") as text_file: 

Solution 3:

In Python3 print() basically adds new line upon every execution. For this purpose I'd suggest you to use sys module's write function. I also had the same problem when I was making a download bar.

Code-

import sys
sys.stdout.write('\r')
sys.stdout.flush()

This should solve your problem.

Post a Comment for "Python Inserts Both A Carriage Return And A Line Feed After Variable, Instead Of Just Line Feed"