Okay, so I have these fruits.txt file
in here, which has these four lines,
which are not fruits anyway, but you get
the idea, it's text. We want to add two
more lines to this existing fruits.txt file.
We don't know what is there at
the moment. If you look at the open
documentation, and scroll down, you will see
[No audio]
here that you can pass different
modes in this argument here. So r
which we used already, we used w, and then
you have x. If you use x
[Author typing]
and try to write, let's say, Okra.
If you execute that,
[No audio]
it's going to say that file
exists. So unlike the w mode, which
overwrite a file, x will not overwrite
the file if the file exists. However, it
cannot append content to an existing
file, because it says that the file
exists. Therefore, we jump to the next
mode, which is a.
[No audio]
You see that Okra was
added there, of course, with a small
issue, because there was not a break
line here in the text, in the existing
text file. So that's some information
you should know, and if you know there
is no break line, then you would need to, let
me save this text file, then you'd need
to add a break line there to get the
correct output. So anytime you add a new
line, you'd need to add a break line in
front. Now, how about reading that content?
[No audio]
Maybe saving it a, save it in a
variable and print out the content. Will
it work? I don't think so. It says that
the operation is not supported, the
file is not readable. It's a, which is
for appending. If you wants to append, to
write and it reads at the same time, you
want to add a '+'.
[No audio]
Just like that,
execute, you get an empty output. Why?
Because of the cursor. So what's
happened is that when we added the
Okra line there, so at first you
created the file, here at this point,
the cursor is here, okay? Then you write
the file. In this line, the cursor goes
to the ends of the file.
[No audio]
So when you read now, you'd read whatever is left under
the last line, which is nothing. What
you can do is myfile.seek, apply a seek
method to put the cursor at the 0
position once again.
In that case, the
cursor will go to the end, it will go
again to the 0 position with this
line, and then you'll read everything
from there and down. So you get the
correct output.
[No audio]