On Mon, 11 Nov 2013 14:51:45 -0800, Rick Johnson wrote: > 2. Never, ever, *EVER* write data to disc before confirming the paths > your passing are pointing to the location you intended to write the > data. Use os.path.exists(path) to test your paths BEFORE trying to write > data.
This is subject to a race condition, which opens you to a security vulnerability: "time of check to time of use" bugs. If you follow Rick's advice, and write code like this: if os.path.exists(path): write_to(path) # custom function to open and write to the file else: handle_missing_file() your code is doubly buggy. First, os.path.exists only tells you if the path exists, not whether it is writable. Perhaps it is on read-only media, or you don't have permission to open it, or it's a directory. Secondly, even if the file exists at the moment you call os.path.exists, there is no guarantee that it will still exist a moment later when you try writing to it. Another process may delete or rename the file, or change permissions in the meantime. So you have to write: if os.path.exists(path): try: write_to(path) except (IOError, OSError): handle_missing_or_locked_file() else: handle_missing_or_locked_file() But now your test doesn't actually accomplish anything. Worse, just because the path *doesn't* exist when you check using exists, that doesn't mean it won't exist by the time you call write_to! Using os.path.exists before opening a file is, for the most part, a waste of time. -- Steven -- https://mail.python.org/mailman/listinfo/python-list