我今天第一次遇到Python with语句。我已经简单地使用Python几个月了,甚至不知道它的存在!鉴于它的地位有些模糊,我认为有必要问一下:
Python with语句是什么 设计用于? 是什么 你用它干什么? 有吗? 我需要注意的问题,还是 相关联的常见反模式 它的使用?在什么情况下try. finally比with更好? 为什么它没有被更广泛地使用呢? 哪些标准库类与它兼容?
我今天第一次遇到Python with语句。我已经简单地使用Python几个月了,甚至不知道它的存在!鉴于它的地位有些模糊,我认为有必要问一下:
Python with语句是什么 设计用于? 是什么 你用它干什么? 有吗? 我需要注意的问题,还是 相关联的常见反模式 它的使用?在什么情况下try. finally比with更好? 为什么它没有被更广泛地使用呢? 哪些标准库类与它兼容?
当前回答
反模式的一个例子可能是在循环内部使用with,而在循环外部使用with会更有效
例如
for row in lines:
with open("outfile","a") as f:
f.write(row)
vs
with open("outfile","a") as f:
for row in lines:
f.write(row)
第一种方法是为每一行打开和关闭文件,与第二种只打开和关闭一次文件的方法相比,这可能会导致性能问题。
其他回答
I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. The with statement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by the with statement and released when you leave the with context. Some examples are: opening files using with open(filename) as fp:, acquiring locks using with lock: (where lock is an instance of threading.Lock). You can also construct your own context managers using the contextmanager decorator from contextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was: from contextlib import contextmanager import os @contextmanager def working_directory(path): current_dir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(current_dir) with working_directory("data/stuff"): # do something within data/stuff # here I am back again in the original working directory Here's another example that temporarily redirects sys.stdin, sys.stdout and sys.stderr to some other file handle and restores them later: from contextlib import contextmanager import sys @contextmanager def redirected(**kwds): stream_names = ["stdin", "stdout", "stderr"] old_streams = {} try: for sname in stream_names: stream = kwds.get(sname, None) if stream is not None and stream != getattr(sys, sname): old_streams[sname] = getattr(sys, sname) setattr(sys, sname, stream) yield finally: for sname, stream in old_streams.iteritems(): setattr(sys, sname, stream) with redirected(stdout=open("/tmp/log.txt", "w")): # these print statements will go to /tmp/log.txt print "Test entry 1" print "Test entry 2" # back to the normal stdout print "Back to normal stdout again" And finally, another example that creates a temporary folder and cleans it up when leaving the context: from tempfile import mkdtemp from shutil import rmtree @contextmanager def temporary_dir(*args, **kwds): name = mkdtemp(*args, **kwds) try: yield name finally: shutil.rmtree(name) with temporary_dir() as dirname: # do whatever you want
这里的答案很棒,但我只想补充一个帮助我的简单答案:
with open("foo.txt") as file:
data = file.read()
Open返回一个文件 自2.6以来,python在文件中添加了__enter__和__exit__方法。 With类似于一个for循环,调用__enter__,运行一次循环,然后调用__exit__ With作用于任何具有__enter__和__exit__的实例
在__exit__关闭文件之前,文件是锁定的,不能被其他进程重用。
来源:http://web.archive.org/web/20180310054708/http: / / effbot.org/zone/python-with-statement.htm
在python中,通常使用" with "语句打开文件,处理文件中的数据,并在不调用close()方法的情况下关闭文件。" with "语句通过提供清理活动简化了异常处理。
with的一般形式:
with open(“file name”, “mode”) as file_var:
processing statements
注意:不需要在file_var.close()上调用close()来关闭文件
反模式的一个例子可能是在循环内部使用with,而在循环外部使用with会更有效
例如
for row in lines:
with open("outfile","a") as f:
f.write(row)
vs
with open("outfile","a") as f:
for row in lines:
f.write(row)
第一种方法是为每一行打开和关闭文件,与第二种只打开和关闭一次文件的方法相比,这可能会导致性能问题。
第1点、第2点和第3点得到了很好的阐述:
4:它相对较新,仅在python2.6+中可用(或python2.5使用from __future__ import with_statement)