令我遗憾的是,我无法弄清楚如何处理python'with'语句的异常.如果我有一个代码:
with open("a.txt") as f:
print f.readlines()
Run Code Online (Sandbox Code Playgroud)
我真的想处理'文件未找到异常'以便进行处理.但我不能写
with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
Run Code Online (Sandbox Code Playgroud)
并且不能写
with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
Run Code Online (Sandbox Code Playgroud)
在try/except语句中包含'with'不起作用:不引发异常.为了以Pythonic方式处理'with'语句内部的失败,我该怎么办?
目前我正在使用这个:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
Run Code Online (Sandbox Code Playgroud)
但问题是旧文件比新文件大.所以我最终得到一个新文件,其中包含旧文件的一部分.
我正在用openPython打开一个文件.我将文件处理封装在一个with语句中:
with open(path, 'r') as f:
# do something with f
# this part might throw an exception
Run Code Online (Sandbox Code Playgroud)
这样我就确定我的文件已关闭,即使抛出了异常.
但是,我想处理打开文件失败的情况(OSError抛出一个).一种方法是将整个with块放在一个try:.只要文件处理代码不引发OSError,这就可以工作.
它可能看起来像:
try:
with open(path, 'rb') as f:
except:
#error handling
# Do something with the file
Run Code Online (Sandbox Code Playgroud)
这当然不起作用,真的很难看.这样做有一种聪明的方法吗?
谢谢
PS:我正在使用python 3.3
我写了一个这样的课:
class FooBar(object):
# some methods
# ...
def __enter__(self, param1, param2):
# do something here ...
pass
Run Code Online (Sandbox Code Playgroud)
我尝试使用我的类(从模块mymod导入):
with (mymod.FooBar("hello", 123)) as x:
# do something here with instance of mymod.FooBar called x ...
pass
Run Code Online (Sandbox Code Playgroud)
当上面的块被执行时,我收到错误:
__enter__() takes exactly 3 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?