Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 5

331 bytes removed, 16:50, 21 February 2018
PART 2 - Writing To Files
<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 (existing) contents inside the file are deleted. This deletion takes place the moment the open() function is executed as opposed , not when writing to the actual writing processth efile. If the file that is being written to doesn't exist, - the file will be created upon the file opening process.<br><br>:#LetCreate a temporary Python file and in there let's open a non-existent file (called file1.txt) for writing:<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:<sourcelang="bash">%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 can use the '''write()''' method for the '''file object'''. 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>
:#Try adding multiple lines:<source lang="python">
f.write('Line 1\nLine 2 is a little longer\nLine 3 is too\n')
</source>Once the '''write()''' method has completed, the final step 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 corrupted or no changes being mademissing file contents.''':<br><source lang="python">
f.close()
</source>
:#Issue the following shell command to view View the contents of the file in the shell to make sure the data was written successfully:<sourcelang="bash">%cat file1.txt</source>You will now create a new file called file2.txt, but this time run multiple write() methods in sequence. You will often write to a file multiple times inside a loop:<br><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:<sourcelang="bash">%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="7">Issue the following shell commands to backup both of your newly-created files and confirm backup:<source lang="bash">
%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:<source lang="python">
f = open('file2.txt', 'w')
%</source><source lang="bash">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 is no longer there?<br></li>
<li>Issue the following shell commands to restore Restore your file from the backup and verify the backup restoration:<source lang="pythonbash">%cp file2.txt.bk file2.txt%cat file2.txt </source>In the event that the data in To avoid overwriting the contents of a file 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')
f.write('This is the 4th line\n')
f.write('Last line in file\n')
f.close()
</source>
<source lang="bash">
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>
f.close()
</source></li>
<li>Issue the following shell command to confirm Confirm that the '''write()''' operation was successful.<source lang="pythonbash">%cat file3.txt
</source></li>
</ol>
:::'''Sample Run 1:'''<source>
rm seneca1.txt seneca2.txt seneca3.txt
python3 ./lab5b.py
First Line
Second Line
lab5b.read_file_string(file1)
# Will print 'First Line\nSecond Line\nThird Line\nFirst Line\nSecond Line\nThird Line\n'
lab5b.write_file_list(file2, list1)
lab5b.read_file_string(file2)
# Will print 'Line 1\nLine 2\nLine 3\n'
lab5b.copy_file_add_line_numbers(file2, file3)
lab5b.read_file_string(file3)
# Will print '1:Line 1\n2:Line 2\n3:Line 3\n'
</source>
::3. Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab5/
pwd #confirm that you are in the right directory
python3 ./CheckLab5.py -f -v lab5b
</source>
::4. Before proceeding, make certain that you identify any and all errors in lab5b.py. When the checking script tells you everything is OK before proceeding - proceed to the next step.
<br><br>