Cleanup when using exceptions and files in python

I have been learning python for a couple of days now and am struggling with my "spirit". I am leaving school from C / C ++ / Java / Perl, and I understand that python is not C (in general), so I am trying to understand the spirit in order to make the most of it (and it’s still difficult) ...

My question is especially focused on handling and clearing exceptions: The code at the end of this post is intended to simulate a fairly common case of opening / parsing a file, where you need to close the file in case of an error ...

Most of the samples I've seen use the else clause from the try statement to close the file ... which made sense to me until I realized that the error could be caused

  • opening itself (in this case there is no need to close the open file)
  • parsing (in which if the file needs to be closed)

The catch here is that if you use the else clause from the try block, then the file never closes if an error occurs while parsing! On the other end, using the "finally" clause, you get the additional necessary verification, because the file_desc variable may not exist if an error occurred during opening (see comments in the code below) ...

This extra check is inefficient and full of crap, because any reasonable program can contain hundreds of characters and analyze the results of dir () - it's a pain in the ass ... Not to mention the lack of readability of such a statement ...

Most other languages ​​allow variable definitions that can save the day here ... but in python everything seems implicit ...

file_desc, try/catch ... , ()... ... ... !

, ?

  • / ? ?
  • - try/except??? ?
  • , file_desc, ... ???
  • close()??? , ?

thanx ... :

class FormatError(Exception):
    def __init__(self, message):
        self.strerror = message
    def __str__(self):
        return repr(message)


file_name = raw_input("Input a filename please: ")
try:
    file_desc = open(file_name, 'r')
    # read the file...
    while True:
        current_line = file_desc.readline()
        if not current_line: break
        print current_line.rstrip("\n")
    # lets simulate some parsing error...
    raise FormatError("oops... the file format is wrong...")
except FormatError as format_error:
    print "The file {0} is invalid: {1}".format(file_name, format_error.strerror)
except IOError as io_error:
    print "The file {0} could not be read: {1}".format(file_name, io_error.strerror)
else:
    file_desc.close()
# finally:
#     if 'file_desc' in dir() and not file_desc.closed:
#        file_desc.close()

if 'file_desc' in dir():
    print "The file exists and closed={0}".format(file_desc.closed)
else:
    print "The file has never been defined..."
+3
5

- , Python 2.5+ . with ; with __exit__. .

try:
    with file("hello.txt") as input_file:
        for line in input_file:
            if "hello" not in line:
                 raise ValueError("Every line must contain 'hello'!")
except IOError:
    print "Damnit, couldn't open the file."
except:
    raise
else:
    print "Everything went fine!"

hello.txt , .

+6

: , :

file_desc = None
try:
    file_desc = open(file_name, 'r')
except IOError, err:
    pass
finally:
    if file_desc:
        close(file_desc)

, Python, ; , Python.

+2

Python 2.5, with, , . . ​​ :

class FormatError(Exception):
    def __init__(self, message):
        self.strerror = message
    def __str__(self):
        return repr(message)


file_name = raw_input("Input a filename please: ")
with open(file_name, 'r') as file_desc:
    try:
        # read the file...
        while True:
            current_line = file_desc.readline()
            if not current_line: break
            print current_line.rstrip("\n")
        # lets simulate some parsing error...
        raise FormatError("oops... the file format is wrong...")
    except FormatError as format_error:
        print "The file {0} is invalid: {1}".format(file_name, format_error.strerror)
    except IOError as io_error:
        print "The file {0} could not be read: {1}".format(file_name, io_error.strerror)

if 'file_desc' in dir():
    print "The file exists and closed={0}".format(file_desc.closed)
else:
    print "The file has never been defined..."
+1

, .  edit: BTW, thanx , ,

. "with as", , :

class FormatError(Exception):
    def __init__(self, message):
        self.strerror = message
    def __str__(self):
        return repr(message)


file_name = raw_input("Input a filename please: ")
try:
    #
    # THIS IS PYTHON SPIRIT... no else/finally
    #
    with open(file_name, 'r') as file_desc:
        # read the file...
        while True:
            current_line = file_desc.readline()
            if not current_line: break
            print current_line.rstrip("\n")
        raise FormatError("oops... the file format is wrong...")
    print "will never get here"
except FormatError as format_error:
    print "The file {0} is invalid: {1}".format(file_name, format_error.strerror)
except IOError as io_error:
    print "The file {0} could not be read: {1}".format(file_name, io_error.strerror)

if 'file_desc' in dir():
    print "The file exists and closed={0}".format(file_desc.closed)
else:
    print "The file has never been defined..."
0

Close , , .

, Python. , .

0
source

Source: https://habr.com/ru/post/1712990/


All Articles