Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 5

78 bytes added, 08:11, 5 September 2017
PART 2 - Writing To Files
::#View the contents of the file2.txt to make sure the write data was saved.<source lang="python">
cat file2.txt
</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 mistake, and accidentally destroy file contents when writing to your file, it is highly 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>
<ol style="margin-left::#80px;"><li value="9">Issue the following command to backup both of your newly-created files and confirm backup:<source lang="python">
cp file1.txt file1.txt.bk
cp file2.txt file2.txt.bk
ls -l file*
</source></li>::#<li>Let's demonstrate what can happen if you perform an incorrect write() operation. Issue the following commands:<source lang="python">
f = open('file2.txt', 'w')
cat file2.txt
</source><br>You should notice that the previous content in your file2.txt file was destroyed. Why do you you think the previous data was destroyed?<br><br></li>::#<li>Issue the following commands to restore your file from the backup and verify the backup restoration:<source lang="python">
cp file2.txt.bk file2.txt
cat file2.txt
</source></li>::#<li>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')
f.write('Last line in file\n')
f.close()
</source></li> ::#<li>The final point to make when writing to files is to make sure that the values being written are strings. This means that before trying to place integers, floats, lists, or dictionaries into a file, first either convert the value using str() or extract the specific strings from items in the list. <source lang="python">
my_number = 1000
my_list = [1,2,3,4,5]
f.write(str(num) + '\n')
f.close()
</source></li>::#<li>View the contents of the file3.txt to make sure the write data was saved.<source lang="python">
%cat file3.txt
1000
4
5
</source></li></ol> 
=== Create a Python Script Demonstrating Writing to Files ===
:'''Perform the Following Instructions'''
13,420
edits