尝试除了打开文件python

时间:2016-04-29 09:45:50

标签: python python-2.7

我正在尝试打开文件并查找值。如果该值不存在,程序将显示错误消息并退出,否则将返回该值。如果该文件不存在,它将处理IOError。这是我的代码片段

{{1}}

当价值不存在时,我总是会得到无,我猜这里错过了一些东西但是看不到它!有什么提示吗?

3 个答案:

答案 0 :(得分:2)

您可以使用next,如果找不到任何内容,则会引发StopIteration例外:

try:
    with open(filename) as myfile:
        return next(line for line in myfile
                    if value in line)
except StopIteration:
    print "Value not found in file"

答案 1 :(得分:1)

值得理解为什么原始存根代码存在问题。

try:                                                                             
            for line in myfile:                                                          
                if value in line:                                                        
                    line = "found line"                                                  
                    return line

如果找到line,则返回line。但是如果找不到line会怎样?经过myfile迭代后,找不到value没有生成错误,因此您不会触发except子句。您的findvalue()将隐式返回None。您的代码的一个小问题修复了该问题:添加return未找到的字符串:

for line in myfile:                                                          
    if value in line:                                                        
        line = "found line"                                                  
        return line                                                          
return "Value not found in file" #or print this out. If you print this out rather than return a value the function will implicitly return a None.

并删除except None as e:

如果您确实想提出错误,请将return "Value not found in file"替换为raise ValueError,并将except None as e替换为except ValueError as e

答案 2 :(得分:0)

for...else流可能在这里很有用,它可以让你在for循环结束时执行代码(doc):

#!/usr/bin/env python2

def findValue(value):
    with open('test_file', "r") as myfile:
        for line in myfile:
            if value in line:
                #line = do_something
                return line
        else:
            raise ValueError, "Value not found in file"

print findValue('a')
findValue('z')

测试文件内容:

$ cat test_file 
abc
def

脚本输出:

$ ./test_script2.py
abc

Traceback (most recent call last):
  File "./test_script2.py", line 16, in <module>
    findValue('z')
  File "./test_script2.py", line 11, in findValue
    raise ValueError, "Value not found in file"
ValueError: Value not found in file

当然,如果你更换&#39; test_file&#39;通过一个不存在的文件,python将引发IOError