[Tutor] Appropriate use of None

Alan Gauld alan.gauld at yahoo.co.uk
Sat Jan 1 07:11:29 EST 2022


On 01/01/2022 11:48, Manprit Singh wrote:

> file = None
> try:
>     file =open("filefortest.txt")
>     text = file.read()
> except IOError:
>     print("File can't be read")
> else:
>     print(text)
> finally:
>     if file != None:
>         file.close()
>         print("File is closed")
> 
> Kindly comment if this kind of practice should be done or not ?

It should not be done because you should use "with" instead
which will automatically close the file.

try:
   with open(...) as infile:
        # process here
except IOError:
   print("File filefortest.txt cannot be opened")
else:
   print("File is closed")

The more unnecessary tests you introduce the more potential
for error.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list