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>Here is a solution that copies existing file content to a temp file. Modifies it as per needs. Then writes back to original file.
Inspiration from <a href="http://stackoverflow.com/questions/17646680/writing-back-into-the-same-file-after-reading-from-the-file">here</a></p>

<pre><code>import tempfile    

filename = "c:\\temp\\File.txt"

#Create temporary file
t = tempfile.NamedTemporaryFile(mode="r+")

#Open input file in read-only mode
i = open(filename, 'r')

#Copy input file to temporary file
for line in i:
  #For "funny" add "Yes"
  if "funny" in line:
      t.write(line.rstrip() + "Yes" +"\n")
  #For "dog" add "No"
  elif "dog" in line:
      t.write(line.rstrip() + "No" +"\n")


i.close() #Close input file

t.seek(0) #Rewind temporary file

o = open(filename, "w")  #Reopen input file writable

#Overwriting original file with temp file contents          
for line in t:
   o.write(line)  

t.close() #Close temporary file
</code></pre>

python python-3.x