Changes

Jump to: navigation, search

OPS435 Python Lab 5

855 bytes added, 09:01, 5 September 2017
PART 2 - Writing To Files
</source>
::#View the contents of the file2.txt to make sure the write data was saved.<source lang="python">
%cat file2.txtLine 1Line 2 is </source><br><blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Make Backup Copies of Your Data Files|Since you might make a little longerLine 3 mistake, and accidentally destroy file contents when writing to your file, it is as wellhighly recommended to make backup copies of your files prior to running your Python scripts. This can be particularly useful when performing any future assignment involving writing to files.}}</blockquote><br>This is ::#Issue the 4th linefollowing command to backup both of your newly-created files and confirm backup:<source lang="python">cp file1.txt file1.txt.bkcp file2.txt file2.txt.bkLast line in ls -l file *
</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')
13,420
edits

Navigation menu