3

I want to append each line in file in python For example:

File.txt

Is it funny?
Is it dog?

Expected Result

Is it funny? Yes
Is it dog? No

Assume that YES, No is given. I am doing in this way:

with open('File.txt', 'a') as w:
            w.write("Yes")

But it appends at the end of file. Not on every line.

Edit 1

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

This is giving the result

Is it funny?
Is it dog?Is it funny?
 Yes Is it dog? Yes 

I do not need this.It is adding new line with appended string. I need

Is it funny? Yes
Is it dog? No
Amar
  • 855
  • 5
  • 17
  • 36

2 Answers2

3

You can write to a tempfile then replace the original:

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")

You could also use fileinput with inplace=True:

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

Output:

Is it funny? Yes
Is it dog? No
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • I need this `Is it funny? Yes Is it dog? No` Not this `Is it funny? Is it dog?Is it funny? Yes Is it dog? Yes ` – Amar Oct 18 '16 at 19:25
  • I added `temp.write(line.rstrip()+" {}\n".format(arg))` in my code and giving `Is it funny? Is it dog?Is it funny? Yes Is it dog? Yes ` – Amar Oct 18 '16 at 19:27
  • @Amar, that is not possible as you can clearly see a newline character added to the string. The only way it is possible is if you have a single line in your file. This is also changing the original file so not sure what you are doing. – Padraic Cunningham Oct 18 '16 at 19:28
  • Is it mandatory to store data in other file and then write it again? – Amar Oct 18 '16 at 19:29
  • @Amar check the file and run the script again , it is giving correct results as posted by Padriac. – R__raki__ Oct 18 '16 at 19:29
  • @Amar, you have to store the data somewhere, a tempfile is about as good as you are going to get. – Padraic Cunningham Oct 18 '16 at 19:49
0

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 here

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
Community
  • 1
  • 1
Anil_M
  • 10,893
  • 6
  • 47
  • 74
  • I need this `Is it funny? Yes Is it dog? No` – Amar Oct 18 '16 at 19:24
  • That is what above will provide , Here are file contents after execution of code: `Is it funny?Yes` `Is it dog?No ` – Anil_M Oct 18 '16 at 19:26
  • 2
    Yes sir. that is what we are doing here. We are copying original file to a temp file. Then updating original file with modified data – Anil_M Oct 18 '16 at 19:29
  • 2
    Two remarks : 1. copying a file line by line is a bit excessive when you could just rename it 2. The syntax `with open(file) as i:` rather than `i = open(file)` gives a cleaner code with a clear visual delimitation of where the file is used. – jadsq Oct 18 '16 at 19:46
  • @Anil_M Kindly elaborate this line `t.seek(0)` `Rewind` means? – Amar Oct 18 '16 at 19:53
  • Anil_M `t = tempfile.NamedTemporaryFile(mode="r+")` makes temporary file in cache? Not should delete it after reading? Is it in memory? – Amar Oct 18 '16 at 19:55
  • @amar - tempfile is deleted as soon as its closed. See here for details : https://docs.python.org/2/library/tempfile.html – Anil_M Oct 19 '16 at 13:55
  • @amar - `t.seek(0) Rewind` let you go to first line of temp file. Remember, we are writing to temp file, so we are at the bottom. Hence need to go to first line before dumping content to original file. See here for details : https://docs.python.org/3/library/tempfile.html – Anil_M Oct 19 '16 at 13:57
  • @Anil_M Thanks dear. – Amar Oct 20 '16 at 03:20