Instructor: Welcome back.
One of the common patterns when working with files
is to actually put them in a try accept block.
So in here we can say, try
and actually put them like this
and try out to see if the file exists.
So we can say except and let's say
FileNotFoundError, which we've seen before.
And here I can say as err
and inside we'll say print
file does not exist.
So that now if I run this,
and remember in our current directory
we don't have sad.text.
If I run this,
I get an error file does not exist.
We can even raise this error if we wanted to.
So we can say raise err.
So now it works as expected
I'll get file does not exist
and then give a FileNotFoundError.
So this is a common way to work with files
to handle different errors.
Another common one with files
is this idea of an IOError
and an IOError usually happens when the computer
or the machine you're on has some issue reading or writing
or doing any sort of IO operation.
So you can have something like IO Error in here
and raise that error if you want.
Again, if I run this FileNotFoundError
if for some reason I give it a weird mode to do
I get an unsupported operation error.
The options are endless
but I hope by now you have an idea of how to do file IO.
But let's do a fun exercise because up until now
we haven't really done anything exciting.
We just read a bunch of texts from a file and that was it.
Nothing that creative, right?
So let's do something fun.
In the next video we're gonna try and build a translator.
That's right, I'll see you in the next video.
Bye bye.