File.close () handling exceptions inside a operator in Python

I know that in Python the file.close() method has no return value, but I cannot find any information about whether an exception is thrown in some cases. If this is not so, then probably the second part of this question is superfluous.

If so, what would be the β€œright” way to handle the file.close() method that throws an exception inside the c statement used to open the file?

Is there a situation where file.close() can fail immediately after the file has been opened and successfully read?

+6
source share
3 answers

Yes, file.close() can throw an IOError exception. This can happen if the file system uses quotas, for example. See the C close() function man page :

Not checking the return value of close() is a common, but nonetheless serious programming error. It is possible that errors in the previous write(2) operation are first reported in the final close() . Do not check the return value when closing the file can lead to silent data loss. This is especially true with NFS and disk quota.

The non-zero return value of the C close() function causes Python to throw an IOError exception.

If you want to handle this exception, put a try...except block around the with statement:

 try: with open(filename, mode) as fileobj: # do something with the open file object except IOError as exc: # handle the exception 

Of course, an IOError could also be thrown at the time of opening.

+4
source

close may throw exceptions, for example, if you run out of disk space while trying to clear your last records, or if you pulled out a USB drive, the file was included.

As for the right way to handle this, it depends on the details of your application. Perhaps you want to show the user an error message. Perhaps you want to close your program. Perhaps you want to repeat everything you did, but with a different file. No matter which answer you choose, it will probably be implemented with a try - except block at any level of your program that is best suited to solve the problem.

+1
source

you can use

 file object = open(file_name [, access_mode][, buffering]) 

Then you check

 file.closed 

It returns True if the file is closed, and false otherwise.

-1
source

All Articles