In this self-check exercise, I'd like you to try
the update process that I presented to you
in the preceding video.
This time, looking specifically for
the last name Doe and updating it to Smith.
Now if by any chance you're switching from
IPython into Jupiter to do the lab exercise
I just want to point out that the Jupiter files
are in a separate folder from where
I've been demonstrating IPython.
So for example I had to copy my accounts.txt file
into the snippets_ipynb folder
in order to demonstrate the solution to this exercise.
So go ahead and try the exercise on your own,
then come back to see the answer.
Okay, let's go ahead and take a look.
As you can see we're first going to open
the accounts.txt file for reading.
And we are going to open a temporary file for writing.
And again we're going to write all of the content
before the record that needs updating
into the temporary file, then we're going to
write the updated record into the temporary file.
Then we're going to write the rest
of the original accounts.txt file into the temporary file,
and then finally we're going to delete the original file
and rename the temporary file as well.
So first let's do the writing process
for which we have the with statement you see here.
And again accounts and temp file
will automatically be closed when
the with statement terminates.
For every record in the accounts file
we're going to split apart the record
into it's three pieces of information,
looking specifically for the record that contains Doe.
If the name does not contain Doe,
then we will simply write the original record out.
Otherwise we will create our new record
by joining together, separated by spaces,
the list of arguments consisting of
account, Smith, and balance.
And again notice that that's in square brackets there
because the join method expects
to receive as an argument a sequence object.
So that'll create the new record,
then we'll write it out to disk,
If it was not the record that needed updating
we'll keep writing out the other records
until the file accounts has been
fully read into memory.
So let's go ahead and execute that.
Now we have our temporary file set up,
and so the next thing we're going to do
is use the operating system module OS
to enable us to remove the original record,
I'm sorry original file, accounts.txt
so now that no longer exists.
Then we're going to rename the original file.
And finally, so that we can check that
the original file does exist and has been updated,
we're going to list out its contents
using a command line command.
Now for those of you on Mac OS and lenox
you can use this first command cat,
otherwise you can use more on Windows.
And you can see that indeed we have the updated record.
And now instead of Doe for record 200
we have the name Smith.
And you can go back and confirm previously
that we had the name Doe in that record.