Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: Writing different sections into a file Date: Mon, 25 Apr 2016 10:48:39 +0200 Organization: None Lines: 31 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de DZdXx/z7woUtxKwNsvskHAkFQOgRwvSwiOme+KZJ1bpQ== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'subject:file': 0.07; '"w")': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'subject:Writing': 0.09; 'subject:into': 0.09; 'advance': 0.10; 'sections': 0.13; 'section.': 0.15; 'fits': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'wrote:': 0.16; 'memory': 0.17; 'body,': 0.22; 'file.': 0.22; 'header': 0.24; 'header:User-Agent:1': 0.26; 'header:X-Complaints- To:1': 0.26; 'dictionary': 0.29; 'point': 0.33; 'url:python': 0.33; 'file': 0.34; 'this?': 0.34; 'list': 0.34; 'url:dev': 0.35; 'url:org': 0.36; 'url:library': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'list.': 0.37; 'data': 0.39; 'format': 0.39; 'easily': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'body': 0.61; 'per': 0.62; 'different': 0.63; 'choose': 0.68; 'url:configparser': 0.84 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd9f11.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Mailman-Original-Message-ID: X-Mailman-Original-References: Xref: csiph.com comp.lang.python:107588 Palpandi wrote: > 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? If the data easily fits into memory just keep it in one list per section header = [...] body = [...] footer = [...] ... body.append("something more\n") footer[:] = ["new footer\n"] ... with open(filename, "w") as f: for section in (header, body, footer): f.writelines(section) If the sections are not known in advance put them into a dictionary or a list. If you are free to choose the file format you may use https://docs.python.org/dev/library/configparser.html