相关疑难解决方法(0)

使用Python'with'语句时捕获异常

令我遗憾的是,我无法弄清楚如何处理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'语句内部的失败,我该怎么办?

python exception-handling

258
推荐指数
4
解决办法
16万
查看次数

用Python读取并覆盖文件

目前我正在使用这个:

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)

但问题是旧文件比新文件大.所以我最终得到一个新文件,其中包含旧文件的一部分.

python file overwrite

95
推荐指数
3
解决办法
15万
查看次数

在Context Manager - Python期间发生捕获异常

可能重复:
使用带有try-except块的python"with"语句

我正在用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

python contextmanager python-3.x

3
推荐指数
1
解决办法
1102
查看次数

__enter __()需要3个参数(给定1个)

我写了一个这样的课:

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)

我究竟做错了什么?

python

2
推荐指数
1
解决办法
1002
查看次数