Protecting against overriding an existing file

Python gives us the ability to open files for writing. By using the w flag, we open a file and truncate its content. This means the file is overwritten with an empty file, and the original content is lost. If you wish to only open a file for writing in case it doesn't exist, you can use the x flag instead, in the following example:

# files/write_not_exists.py
with open('write_x.txt', 'x') as fw:
fw.write('Writing line 1') # this succeeds

with open('write_x.txt', 'x') as fw:
fw.write('Writing line 2') # this fails

If you run the previous snippet, you will find a file called write_x.txt in your directory, containing only one line of text. The second part of the snippet, in fact, fails to execute. This is the output I get on my console:

$ python write_not_exists.py
Traceback (most recent call last):
File "write_not_exists.py", line 6, in <module>
with open('write_x.txt', 'x') as fw:
FileExistsError: [Errno 17] File exists: 'write_x.txt'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.79.59