Replace newline in python when reading line for line
<p>I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\n' ' '.  Basically to get all of the lines on a single line. In python print line is a bit different from what I understand.  re.sub cannot find my new line because it doesn't exist even though when I print to an output it does.  Can someone explain how I can work around this issue in python?</p>

<p>Here is my code so far:</p>

<pre><code># -*- iso-8859-1 -*-
import re
def proc():
    f= open('out.txt', 'r')
    lines=f.readlines()
    for line in lines:
        line = line.strip()
        if '[' in line:
            line_1 = line
            line_1_split = line_1.split(' ')[0]
            line_2 = re.sub(r'\n',r' ', line_1_split)
            print line_2
proc()
</code></pre>

<p>Edit:  I know that "print line," will print without the newline. The issue is that I need to handle these lines both before and after doing operations line by line. My code in shell uses sed, awk and tr to do this.</p>

<p>Using <code>with</code> ensures you close the file after iteration.</p>

<p>Iterating saves memory and doesn't load the entire file.</p>

<p><code>rstrip()</code> removes the newline in the end.</p>

<p>Combined:</p>

<pre><code>with open('out.txt', 'r') as f:
    for line in f:
        print line.rstrip(),
</code></pre>

python regex newline python-2.x