Hey welcome again and this would be a very short lecture and what you're going
to learn now is how to use the with statement now what with statement does is
it lets you write cleaner code when handling false with Python so that's one thing
and the second thing is that the with statement makes sure that the file is
closed without you having to write a close method explicitly, and yeah.
This is what I mean. So everything starts with with and then
you use the same method, so open to open a file and you say example dot txt and let
me use methods, maybe append plus for reading and appending and you say as file
so you create a variable on the fly and notice the column there which will
underlies that you need to indent the code under that, so every time you have a
column in Python everything that goes after the column is indented, and these lies
now are part of the with statement block. So we're talking about a block of code
in here and then you do the same thing as you do with a normal file handling
except of when you finish this block you don't have to close the file.
So what we could do is you know with the a plus method when you open a file with
a plus method and then you want to read that file the pointer will be at this
point currently, so if you read now, you'll read an empty string so what you
do first is maybe file seek and 0 there. That would place the pointer at the first
line and just there. Okay and execute that. Then you could do content equals
to file dot read and what that will do it will create a variable we named
content and then you can reuse that variable inside the with statement
or outside of it, so the variable stays there and then maybe write something
there, write. Probably we need a brake line there.
And then, line 6, yeah 6. Execute. Execute again and you're done.
the file, the changes will be written in the file once the block of code ends,
so the syntax is similar to when you write a for loop with this indentation in here
and our content you see that you have this line there.
And also if you open example.txt again you see that line 6 is there.
And yeah, that's about the with statement. In other scenarios you'd want to use file.close
especially if you have a long code to write, if you want to open a file in the
beginning and then you do a lot of work with that file, so maybe you'll be
interested it to keep the file open. But for quicker writing and reading use
the with statement because that will make your code looks cleaner.
Yeah, that closes this lecture and hope you learn from it and I hope you enjoy the course
and please leave a review if you're feeling like so. I would appreciate that.
And yeah, I'll see you in the next lectures. We have more to go and still a lot of
things to learn. I'll talk to you later.