Append each line in file
<p>I want to append each line in file in <code>python</code> For example:</p>

<p><strong>File.txt</strong></p>

<pre><code>Is it funny?
Is it dog?
</code></pre>

<p><strong>Expected Result</strong></p>

<pre><code>Is it funny? Yes
Is it dog? No
</code></pre>

<p>Assume that YES, No is given. I am doing in this way:</p>

<pre><code>with open('File.txt', 'a') as w:
            w.write("Yes")
</code></pre>

<p>But it appends at the end of file. Not on every line.</p>

<p><strong>Edit 1</strong></p>

<pre><code>with open('File.txt', 'r+') as w:
            for line in w:
                w.write(line + " Yes ")
</code></pre>

<p>This is giving the result</p>

<pre><code>Is it funny?
Is it dog?Is it funny?
 Yes Is it dog? Yes 
</code></pre>

<p>I do not need this.It is adding new line with appended string.
I need </p>

<pre><code>Is it funny? Yes
Is it dog? No
</code></pre>

<p>You can write to a <em>tempfile</em> then replace the original:</p>

<pre><code>from tempfile import NamedTemporaryFile
from shutil import move
data = ["Yes", "No"]
with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    # pair up lines and each string
    for arg, line in zip(data, f):
        # remove the newline and concat new data
        temp.write(line.rstrip()+" {}\n".format(arg))

# replace original file
move(temp.name,"in.txt")
</code></pre>

<p>You could also use <em>fileinput</em> with <em>inplace=True</em>:</p>

<pre><code>import fileinput
import sys
for arg, line in zip(data, fileinput.input("in.txt",inplace=True)):
    sys.stdout.write(line.rstrip()+" {}\n".format(arg))
</code></pre>

<p>Output:</p>

<pre><code>Is it funny? Yes
Is it dog? No
</code></pre>

python python-3.x