December 2018
Beginner to intermediate
796 pages
19h 54m
English
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.pywith open('write_x.txt', 'x') as fw: fw.write('Writing line 1') # this succeedswith 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. ...
Read now
Unlock full access