Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 5
    This answer is wrong. os.path.exists returns true for things that aren't files, such as directories. This gives false positives. See the other answers that recommend os.path.isfile. Commented Aug 1, 2015 at 13:54
  • 6
    On your third example, I create a link named filepath with the right timing, and BAM, you overwrite the target file. You should do open(filepath, 'wx') in a try...except block to avoid the issue. Commented Aug 24, 2015 at 14:05
  • 1
    In your second example, at least in Windows, you will get an OSError if filepath + '.old' already exists: "On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file." Commented May 24, 2016 at 14:14
  • @TomMyddeltyn: As of Python 3.3, os.replace portably performs silent replacement of the destination file (it's identical to os.rename's Linux behavior) (it only errors if the destination name exists and is a directory). So you're stuck on 2.x, but Py3 users have had a good option for several years now. Commented Nov 29, 2017 at 18:14
  • On the rename example: It should still be done with try/except. os.rename (or os.replace on modern Python) is atomic; making it check then rename introduces an unnecessary race and additional system calls. Just do try: os.replace(filepath, filepath + '.old') except OSError: pass Commented Nov 29, 2017 at 18:17