Changes

Jump to: navigation, search

OPS435 Python Lab 5

44 bytes removed, 22:56, 10 September 2017
PART 2 - Writing To Files
:Up to this point, you have learned how to access text from a file. In this section, you will learn how to write text to a file. Writing data to a file is useful for creating new content in a file or updating (modifying) existing data contained within a file.
 
:'''Perform the Following Steps:'''
<blockquote style="margin-left:35px;">{{Admon/caution|style="padding-left:25px"|Risk of Losing File Contents|A common problem that new Python programmers may encounter is to accidentally erase existing contents of a file when writing new data to a file. When opening files for writing (using the ''''w'''' open function option), Python assumes existing content in the file is no longer wanted and it's immediately deleted; therefore, if you wish to write data to a file but keep existing content, you need to use the open file option ''''a'''' (append new data to a file).}}</blockquote>
::#To start, open the ipython3 shell:<source lang="python">
ipython3
</source>When opening a file for writing, the ''''w'''' option is specified with the '''open()''' function. When the 'w' option is specified, previous contents inside the file are deleted. This deletion takes place the moment the open() function is executed as opposed to the actual writing process. If the file that is being written to doesn't exist, the file will be created upon the file opening process.<br><br>
::#Let's open a non-existent file (called file1.txt) for writing. Issue the following command:<source lang="python">
f = open('file1.txt', 'w')
</source>
::#To confirm that the new file now exists and is empty, issue the following shell command:<source lang="python">%ls -l file1.txt</source>The '''ls -l''' command should work, but if you experience any problems, place a % sign in front of the command. This represents the '''alias''' for the ''ls -l'' command (i.e. '''%ls -l''').<br><br>To add lines of text to the file, you would can use the '''write()''' method for the '''file object'''. For safe file management, always Typically you end every line in a text file with the special character ''''\n'''' to represent a "new line". Multiple lines may also be placed inside a single write operation: simply put the special character ''''\n'''' wherever a line should end.<br><br>::#To demonstrate Try adding multiple lines, issue the following command:<source lang="python">
f.write('Line 1\nLine 2 is a little longer\nLine 3 is too\n')
</source>Once the '''write()''' operation method has been runcompleted, the final step would be is to '''close()''' the file. The file MUST be closed properly or else data will not consistently be written to the file. '''NOTE: Not closing a file can lead to corruption or not no changes being made.''':<br><br>::#Issue the following command to close our file:<source lang="python">
f.close()
</source>
::#Issue the following shell command to view the contents of the file to make sure the write data was saved. written successfully:<source lang="python">%cat file1.txt # or %cat file2.txt to display the same results as the cat command</source>You will now create a new file called file2.txt, but run multiple write() methods in a series of operationssequence. The ability You will often write to write() a file multiple lines like this allows for writes to take place times inside '''loops''' and more complex programs to continuously write to a file.<br>loop:<br>::#Issue the following commands:<source lang="python">
f = open('file2.txt', 'w')
f.write('Line 1\nLine 2 is a little longer\nLine 3 is as well\n')
f.close()
</source>
::#Issue the following shell command to confirm that the contents were written to file2.txt:<source lang="python">%cat file2.txt
</source>
<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><blockquote style="margin-left:35px;">{{Admon/caution|style="padding-left:25px"|Make Backup Copies of ALL your files|Since you are now writing code that opens files for writing you may accidentally truncate the wrong file (like your assignment file, for example). Make regular backups of all your work. Just copy it to a USB stick or if you're bored - learn version control.}}</blockquote><br><ol style="margin-left:80px;"><li value="97">Issue the following command shell commands to backup both of your newly-created files and confirm backup:<source lang="pythonbash">%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>You should notice that the previous content in your file2.txt file was destroyed. Why do you you think the previous data was destroyedis no longer there?<br></li><li>Issue the following shell 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>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.<br><br></li>
<li>To demonstrate, issue the following commands:<source lang="python">
f = open('file1.txt', 'a')
cat file1.txt
</source>The final thing to consider when writing to files is to make certain 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()''' function or extract the specific strings from items in the list.<br><br></li>
<li>To see how to In this example we convert a single number and all the numbers into in a list to strings before writing them to be stored into a file, issue the following commands:<source lang="python">
my_number = 1000
my_list = [1,2,3,4,5]
f.close()
</source></li>
<li>Issue the following shell command to confirm that the '''write()''' operation was successful.<source lang="python">cat file3.txt # or %cat file3.txt
</source></li>
</ol>

Navigation menu