Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!newsfeed.xs4all.nl!newsfeed3a.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!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.006 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'exists.': 0.07; 'rename': 0.07; 'subject:file': 0.07; 'overwrite': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'python': 0.11; 'suggest': 0.14; 'wrote': 0.14; 'received:80.91.229.3': 0.16; 'received:plane.gmane.org': 0.16; 'tempfile': 0.16; 'module': 0.19; 'file,': 0.19; 'version.': 0.19; 'specify': 0.24; 'least': 0.26; 'header:X-Complaints-To:1': 0.27; 'see,': 0.30; "i'm": 0.30; 'catching': 0.31; 'file': 0.32; 'cases': 0.33; 'could': 0.34; 'problem': 0.35; 'problem.': 0.35; 'case,': 0.35; 'but': 0.35; 'there': 0.35; 'really': 0.36; 'done': 0.36; 'too': 0.37; 'two': 0.37; 'to:addr:python-list': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'simple': 0.61; 'save': 0.62; "you'll": 0.62; 'name': 0.63; 'different': 0.65; 'tough,': 0.84; 'subject::': 0.85; 'subject:Save': 0.91 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Dave Angel Subject: Re:Save to a file, but avoid overwriting an existing file Date: Wed, 12 Mar 2014 14:22:51 -0400 (EDT) Organization: news.gmane.org References: X-Gmane-NNTP-Posting-Host: dpc6744198232.direcpc.com X-Newsreader: PiaoHong Usenet NewsReaders 1.36 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: 25 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1394648316 news.xs4all.nl 2903 [2001:888:2000:d::a6]:41945 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:68290 zoom Wrote in message: > Hi! > > I would like to assure that when writing to a file I do not overwrite an > existing file, but I'm unsure which is the best way to approach to this > problem. As I can see, there are at least two possibilities: > > 1. I could use fd = os.open("x", os.O_WRONLY | os.O_CREAT | os.O_EXCL) > which will fail - if the file exists. However, I would prefer if the > program would try to save under different name in this case, instead of > discarding all the calculation done until now - but I' not too well with > catching exceptions. > The tempfile module is your best answer, but if you really need to keep the file afterwards, you'll have the same problem when you rename it later. I suggest you learn about try/except. For simple cases it's not that tough, though if you want to ask about it, you'll need to specify your Python version. -- DaveA