user1423015
user1423015

Reputation: 653

string append in python

i am trying to prepend each line of a file with " (2 spaces/tabs after ") and append with string- "\r\n"+". the lines of the file before this operation looks like as folllows.

        <!--You have a CHOICE of the next 5 items at this level-->
        <!--Optional:-->
        <urn:Account id=\"?\">
           <!--Optional:-->
           ............
           .............    

I am using the following code,

inf=open("req.txt","r")

outf=open("out.txt","w")

for line in inf.readlines():

    outf.write("\"          "+line+"\\r\\n\" +")

inf.close()

outf.close()

prepending is happening as expected but appending is not happening properly. Final result was all lines were prepended with - \r\n" +" except the first line. first line was prepended with only " .

I want each line prepended with " and appended with "\r\n"+"

Upvotes: 2

Views: 1194

Answers (2)

ninMonkey
ninMonkey

Reputation: 7511

Is there a reason you are not using a xml module to read/write the xml file? Because it could simplify your code.

Edit: Here's a PyMOTW ElementTree tutorial, and the Docs python.org/xml.etree.ElementTree

Upvotes: 1

OmnipotentEntity
OmnipotentEntity

Reputation: 17131

You should probably use python's built in string formatting.

outf.write("%s%s%s" % ('"          ', line, '\r\n" +'))

However! You're not removing the newlines from your data before changing it. As a result you're getting your format, the entire line (including the newline) and then your second part.

You'll want to run it through python's built in rstrip method.

outf.write("%s%s%s" % ('"          ', line.rstrip(), '\r\n" +'))

One thing you want to watch out for is that rstrip will remove any white space, if you want to remove just newlines then you can use:

outf.write("%s%s%s" % ('"          ', line.rstrip("\r\n"), '\r\n" +'))

However, once you do this, you'll need to put a new line at the end of your string again.

outf.write("%s%s%s%s" % ('"          ', line.rstrip("\r\n"), '\r\n" +', "\r\n"))

However! Depending on your OS your default line ending may be different, to do it correctly you'll want to import os then:

outf.write("%s%s%s%s" % ('"          ', line.rstrip(os.linesep), '\r\n" +', os.linesep))

Upvotes: 1

Related Questions