1,234
edits
Changes
→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.
<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>
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>
f = open('file1.txt', 'w')
</source>
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>
f = open('file2.txt', 'w')
f.write('Line 1\nLine 2 is a little longer\nLine 3 is as well\n')
f.close()
</source>
</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>