Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.xs4all.nl!newsfeed2.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.005 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'output': 0.05; 'received:134': 0.05; 'subject:code': 0.07; 'subject:file': 0.07; 'input,': 0.09; "subject:, '": 0.09; 'try:': 0.09; 'csv': 0.16; 'input:': 0.16; 'subject: \n ': 0.16; 'header:User-Agent:1': 0.23; 'this:': 0.26; 'header:In-Reply-To:1': 0.27; 'wondering': 0.29; "i'm": 0.30; 'file:': 0.31; 'file': 0.32; 'open': 0.33; 'subject:the': 0.34; 'could': 0.34; 'subject:with': 0.35; 'except': 0.35; 'something': 0.35; 'false': 0.36; 'subject:?': 0.36; 'hi,': 0.36; 'skip:o 20': 0.38; 'subject:new': 0.38; 'to:addr:python-list': 0.38; 'to:addr:python.org': 0.39; 'subject:Using': 0.84; 'victor': 0.84 X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: Ap8EADe6cFKGuA9G/2dsb2JhbABZwFuCeoEzgxoBBXgRCyEWDwkDAgECAUUTCAKIA7FLiRSPVhaEFgOYCoYpi2CBaIE/ Date: Wed, 30 Oct 2013 08:53:41 +0100 From: Antoon Pardon User-Agent: Mozilla/5.0 (X11; Linux i686; rv:10.0.12) Gecko/20130116 Icedove/10.0.12 MIME-Version: 1.0 To: python-list@python.org Subject: Re: Using "with open(filename, 'ab'):" and calling code only if the file is new? References: <68bd6cb6-44b2-446c-b0e2-043e3ac1c35b@googlegroups.com> In-Reply-To: <68bd6cb6-44b2-446c-b0e2-043e3ac1c35b@googlegroups.com> Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 29 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1383119629 news.xs4all.nl 15910 [2001:888:2000:d::a6]:48690 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:58010 Op 30-10-13 02:02, Victor Hooi schreef: > Hi, > > I have a CSV file that I will repeatedly appending to. > > I'm using the following to open the file: > > with open(self.full_path, 'r') as input, open(self.output_csv, 'ab') as output: > fieldnames = (...) > csv_writer = DictWriter(output, filednames) > # Call csv_writer.writeheader() if file is new. > csv_writer.writerows(my_dict) > > I'm wondering what's the best way of calling writeheader() only if the file is new? If you are using 3.3 you could use something like this: with open(self.full_path, 'r') as input: try: output = open(self.output_csv, 'abx') new_file = True except FileExistsError: output = open(self.output_csv, 'ab') new_file = False fieldnames = (...) csv_writer = DictWriter(output, filednames) if new_file: csv_writer.writeheader() csv_writer.writerows(my_dict)