Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha) 
x=(a+b+c for a in alpha for b in alpha for c in alpha) 
y=(a+b for a in alpha for b in alpha) 
z=(a for a in alpha ) 
with open("Output.txt", "w") as text_file: 
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')

the problem here is the line

print("{}\r".format(k), file=text_file, end='')
like image 676
TkrZ Avatar asked Oct 18 '25 14:10

TkrZ


1 Answers

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 os
print(os.linesep)

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

To prevent this, open the file in binary mode.

with open("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.

like image 154
Simon Hibbs Avatar answered Oct 21 '25 17:10

Simon Hibbs