Python file modes: Use ‘x’ instead of ‘w’ to avoid overwriting

Python file modes: Use 'x' instead of 'w' to avoid overwriting

Write to a file in Python with open(filename, ‘w’).

What if filename already exists? Its contents are gone. (I hope you have backups!)

Instead, try:

open(filename, 'x')

If filename already exists, ‘x’ raises an exception. For new files, ‘x’ and ‘w’ are the same.