On 25/04/2016 17:00, justin walters wrote:
On Mon, Apr 25, 2016 at 3:04 AM, Karim <kliat...@gmail.com> wrote:


On 25/04/2016 09:30, Palpandi wrote:

Hi,

I need to write different sections into a file.
At any point of time, content can be added to any section.

I don't want keep each section into a temporary file.
What is the better way to store the contents of each section and write
them into a file at the end?
What is the better datatype to achieve this?


Thanks and Regards,
Palpandi

Use Stringio:
-

from cStringIO import StringIO

content = StringIO()

# Header
content.write('; Header\n')
content.write('; Body'\n)
content.write('; Footer\n')

open('my_file', 'wb').write(content.getvalue())

-
Karim


--
https://mail.python.org/mailman/listinfo/python-list


All of the other answers are great too. I was thinking that you could
format the text file to have dividers for each section. For instance it may
look something like this:

Header
Lorem ipsum....
<--->
Body
Lorem ipsum...
<--->
Footer
Lorem ipsum..

Then, you could create a list of sections like so:

file = open('file.txt', 'r').read()

section_list = file.split('<--->')

print(section_list[0])

Header
Lorem ipsum...

Say you wanted to get really fancy, you could even format the file to have
named sections like so:

<section name="Header">
     <content>Lorem ipsum...</content>
</section>
<section name="Body">
     <content>Lorem ipsum...</content>
</section>
<section name="footer">
     <content>Lorem ipsum...</content>
</section>

Then you can use the xmlparser library to parse the file into an xml object.


Alternatively, you could also use JSON formatting:

{
     sections: {
         header: {
             title: "header",
             content: "Lorem ipsum..."
         },
         body: {
             title: "Body",
             content: "Lorem ipsum..."
         },
         footer: {
             title: "Footer",
             content: "Lorem ipsum..."
         }
     }
}

I hope this helps.

Great ideas!

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to