除外语句

-2 投票
4 回答
633 浏览
提问于 2025-04-17 00:01

在一个叫做 check_price() 的函数里,我试着打开一个不存在的 .txt 文件来读取内容,我想用 except 语句来捕捉到输入输出错误(IOerror)。

但是后来我创建了一个 .txt 文件,想用同样的函数来读取它。然而我的函数却无法读取这个文件。有没有人能帮我一下?

我应该做一个价格检查程序。

示例看起来是这样的。

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.  

我的函数:

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 ""

4 个回答

0

你没有写任何代码来处理成功打开文件后的情况。所有在 break 之后的代码仍然属于 except: 这个部分。你需要调整一下代码的缩进。

0

你说的“没有读取文件”是什么意思呢?另外,为什么在break语句后面还有代码呢?

我猜文件没有被读取是因为你在缩进上出了错,把break后面的代码缩进成和except块一样的级别了。其实这些代码应该在except块之后,缩进要少一些。试着把那段多余的代码放到try块里,或者删掉多余的文件打开代码,并减少缩进。

我觉得你的错误在于你忘了break是用来结束当前的循环迭代的,break后面的所有代码都不会被执行。

3

这里有两个问题。第一个是打开文件的方式,第二个是用while语句来打开文件。如果你仔细想想,其实你不想一直反复打开和关闭同一个文件。最好的做法是打开一次,读取每一行,然后再关闭它。所以你的读取函数可能看起来像这样:

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

还有一些设计上的问题,主要是关于如何处理异常。如果出现了输入输出错误(IOError),你是在这个函数里处理,还是让这个错误“向上抛”到上面的函数去处理?上面的函数可能是在你的用户界面里,这里应该处理这些错误信息。问题在于,如果你在这样的函数里处理错误,你就得维护一份自己的异常错误代码列表,这样会增加你的维护负担……这就看你自己怎么选择了。

不过,我想指出还有另一种处理文件读取的方法,这种方法更好,并且在更新版本的Python中出现了。它是这样的:

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.

我个人比较喜欢这种方法。with语句控制着从open得到的f对象的生命周期,这样你就不用记得去关闭它了。

撰写回答