[No audio]
Let's take a look at the help
documentation of open,
and you'll see that the open function gets a bunch of
arguments. The first two are the most
important ones. We already used file,
which is the path to the file object,
and for these other ones, we use their
default values, which means for modes, we
used r, r means read, therefore, this
quote here is the same as
[No audio]
this.
[No audio]
So you get the same output. Which one should
you use? Well, for to make the code
simpler and shorter, this is fine. To
make the code more explicit in terms of
readability so that others can see that
this is about reading the code, then
you'd use this, either way is fine. Now
what can we use for writing? For writing,
you'd use w for write and let me
[No audio]
create a new file under the files folder, call
it vegetables. So a vegetables file
doesn't exist currently in my files
folder. This will be created by the open
function. And then in that empty file,
we're going to write something, write
[No audio]
Tomato. Of course, the content variable
doesn't make sense here, because we're
not fetching some data from the file,
we're just writing there. So let's keep
it like that, Save it,
execute, and a
vegetables.txt file has been created
in my computer with a Tomato string
there. Let me put it here. So the read
method looks for an existing file, the
write method creates a new file, and I
should warn you that if the file exists,
like in this case, fruits.txt is
there, if that is the case, Python will
overwrite the existing file. So if you
open fruits.txt now, you'll see that
you have this new content of the file.
[No audio]
So the existing content is discarded.
How can we write more lines? Well, we
have to use the backslash n special
string which creates break lines.
[No audio]
Onion, execute. So this is fruits.txt.
[No audio]
And you get these three lines as we expected.
[No audio]
Something, you should know is that
[No audio]
you can apply more than one method
to the open file. Let's write Garlic here.
[No audio]
Now intentionally, I didn't do
something I was supposed to do to show
you what happens. So Garlic was
immediately put after Onion because
there is no space or a backslash n
operator there. If I put a space here,
you of course, it gets a space between
Onion and Garlic. But what you want
instead is you want that after each line
you write, you want a backslash n, and in
that case, you'd get the correct output.
So now you're probably wondering, well,
I have this fruits.txt file, I don't
want to overwrite it. How can I actually
add another line under this existing
lines? And I'll show you how to do that
in the next video.
[No audio]