TAGS :Viewed: 4 - Published at: a few seconds ago

[ 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-->
        <urn:Account id=\"?\">

I am using the following code,



for line in inf.readlines():

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



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

Answer 1

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

Answer 2

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