开发者

Except statement

In a function check_price() I try to open a .txt file, that does not exist, to read and I wanted to开发者_如何学JAVA use except statement to catch the IOerror.

But after, I created a .txt file and I want to use the same function to read it. However my function doesn't read the file. Can anyone help me?

I'm suppose to make a price checker program.

The sample looks like this.

Menu:
(I)nstructions  
(L)oad Products  
(S)ave Products  
(A)dd Product  
(C)heck Prices  
(Q)uit  
>>> C  
No products.  

Menu:  
(I)nstructions  
(L)oad Products  
(S)ave Products  
(A)dd Product  
(C)heck Prices  
(Q)uit  
>>> L  
Enter file name: products.txt  

Menu:  
(I)nstructions  
(L)oad Products  
(S)ave Products  
(A)dd Product  
(C)heck Prices  
(Q)uit  

>>> c  
Huggies is $0.39 per unit.  
Snugglers is $0.26 per unit.  
Baby Love is $0.23 per unit.  

My function:

def check_price():
        while True:
            try:
                text_file = open("product.txt",'r')
                break
            except IOError:
                print"no product"
                text_file = open("product.txt",'r')
                line = text_file.readline()
                if line == "":
                    break
                print ""


There are two problems. One, where you open the file, and two, the use of the while statement to open the file. If you think about it logically, you don't want to keep re-opening and closing that file, really. Just open it once, read each line from it, and close it. So your reading function might look like this:

def check_price(file_path):

    # try and open the file. If there's an exception, return an error
    try:
        f = open(filepath, "r")
    except IOError as e:
        # do something with e, possibly.
        # could return an error code?
        # could raise an exception?
        # could not do anything and let the parent function 
        # handle the exception:
        return -1

    # read until no more lines appear
    while True:
        line = f.readline()
        if not line:  # not x is true in python for False, "", []
            break

        # process that line

    f.close()  # don't forget this

There are some design questions regarding how you handle exceptions. If there's an IOError, do you handle them here, in the function, or not, meaning the exception "propagates" up to the function above. That function might well be in your user interface, where such error messages ought to be processed. The problem with handling them in functions like this is that you then have to maintain a list of exception error codes of your own, adding to your maintenance burden... up to you, that one.

I should point out another way of handling file reads, however, which is nicer and appears in newer versions of python. Here it is:

def check_price(file_path):

    with open(filepath, "r") as f:
        while True:
            line = f.readline()
            if not line: 
                break
            # process line

    # here, at the same level of indentation as the with statement,
    # f has been automatically closed for you.

I personally like this approach. The with statement controls the life of the f object that results from open such that you don't have to remember to close it.


What do you mean by does not read the file? That aside, Why is there code after the break statement?

I suppose the file isn't read since you made an indentation mistake giving the lines following the break statement the same indentation as the except block while they should've appear after the except block with a lesser level of indentation. try moving that extra code into the try block or remove the extra file opening and decrease the code indentation level.

I think your error is in the fact you forgot the break exits the current iteration of the while loop and all the code after it will not be executed.


You don't have any code that would run after successfully opening the file. All the code after break is still part of the except: block. Fix your indentation.


The function is nonsensical. There's no reason to use a while loop here. In particular, it looks very easy for the logic to get into an infinite loop.

Here are some suggestions:

  1. I would avoid the try/except and just check the existence of the file directly, using os.path.exists.

  2. If the file doesn't already exist, create it. Using open with "r" does not automatically create a file. See open()'s documentation. I think you want to use "w" instead here, just to force file creation. But you only want to do this if the file doesn't already exist, because otherwise you'll truncate the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜