13,420
edits
Changes
→PART 2 - Writing To Files
</source>
::#View the contents of the file2.txt to make sure the write data was saved.<source lang="python">
</source>
::#View Let's demonstrate what can happen if you perform an incorrect write() operation. Issue the contents of following commands:<source lang="python">f = open('file2.txt', 'w')cat file2.txt </source><br>You should notice that the file1previous content in your file2.txt file was destroyed. Why do you you think the previous data was destroyed?<br><br>::#Issue the following commands to make sure it has restore your file from the original data backup and has not been changedverify the backup restoration:<source lang="python">%cp file2.txt.bk file2.txtcat file1file2.txtLine 1Line 2 is a little longerLine 3 is as well
</source>
::#In the event that the data in the file is important and should not be overwritten, we can '''append ''' data to the end of the file instead. Use the option 'a' instead of 'w' to perform appending.<source lang="python">
f = open('file1.txt', 'a')
f.write('This is the 4th line\n')