python打开文本文档
Python with statement allows us to write simpler code when working with context managers. The with statement was introduced in Python 2.5 under PEP 343.
Python with语句使我们在与上下文管理器一起工作时可以编写更简单的代码。 with语句是在PEP 343下的Python 2.5中引入的。
(1. What is a Context Manager?)
A context manager is an object that creates and manages a runtime context. The typical usage of context managers is to save and restore the global state, lock and unlock resources, opening and closing files, etc.
上下文管理器是创建和管理运行时上下文的对象。 上下文管理器的典型用法是保存和还原全局状态,锁定和解锁资源,打开和关闭文件等。
(2. The lifecycle of Context Manager)
The context manager object must define the enter() and exit() methods. These methods are called when the runtime context is created and when it’s destroyed.
上下文管理器对象必须定义enter()和exit()方法。 创建运行时上下文以及销毁它们时将调用这些方法。
(3. Why do we need Python with statement?)
When we have to work with a file, we have to first open it. It creates a runtime context manager for the file. After the work is done, we have to manually close the file so that the context manager terminates properly.
当我们必须使用文件时,我们必须首先打开它。 它为文件创建一个运行时上下文管理器。 工作完成后,我们必须手动关闭文件,以便上下文管理器正确终止。
We generally use the try-except block to work with the file and finally block to close the file. This makes sure that the file gets closed even if there is an error raised by the try block.
我们通常使用try-except块来处理文件,最后使用块来关闭文件。 这样可以确保即使try块引发错误,文件也可以关闭。
try:
txt_file = open("abc.txt")
# do some operations
txt_file.close()
except FileNotFoundError as e:
print(e)
finally:
txt_file.close()
Python with statement takes care of calling the exit() method of the context manager when the code inside the with block is executed.
执行with块中的代码时,Python with语句负责调用上下文管理器的exit()方法。
Let’s rewrite the above code using the with statement.
让我们使用with语句重写上面的代码。
with open("abc.txt") as file:
# do some operations
print("Done")
The code is much simpler to read and we don’t have to worry about closing the file every time.
该代码更易于阅读,我们不必担心每次都关闭文件。
(4. Python with Statement Custom Context Manager Example)
We can define our own custom context manager by implementing enter() and exit() methods.
我们可以通过实现enter()和exit()方法来定义自己的自定义上下文管理器。
class MyContext:
def __init__(self):
print("init method of MyContext")
def __enter__(self):
print("entering context of MyContext")
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit context of MyContext")
with MyContext() as my_context:
print("my_context code")
Output:
输出:
init method of MyContext
entering context of MyContext
my_context code
exit context of MyContext
- The context manager is initialized.
- Then the __enter__() method is called for the context manager object.
- The code inside the with block is executed.
- Finally, the __exit__() method of the context manager is called.
(5. Python with open files)
Python 3.1 enhanced the with statement to support multiple context managers. Let’s see how to open multiple files using the with statement.
Python 3.1增强了with语句,以支持多个上下文管理器。 让我们看看如何使用with语句打开多个文件。
with open("abc.txt") as file1, open("abc.txt") as file2:
pass
The above code is equivalent to multiple nested with statements.
上面的代码等效于多个嵌套的with语句。
with open("abc.txt") as file1:
with open("abc.txt") as file2:
pass
(6. Python with statement exception scenarios)
If there is an exception raised in the with block, its type, value, and traceback are passed as arguments to __exit__().
如果with块中引发了异常,则将其类型,值和回溯作为参数传递给__exit __()。
If the __exit__() method returns False, then the exception is re-raised.
如果__exit __()方法返回False,则重新引发异常。
class MyContext:
def __init__(self):
print("init method of MyContext")
def __enter__(self):
print("entering context of MyContext")
def __exit__(self, exc_type, exc_val, exc_tb):
print(f'exit context of MyContext - {exc_type} :: {exc_val} :: {exc_tb}')
return False
with MyContext() as my_context:
print("my_context code")
raise TypeError("TypeError inside with block")
Output:
输出:
init method of MyContext
entering context of MyContext
my_context code
exit context of MyContext - <class 'TypeError'> :: TypeError inside with block :: <traceback object at 0x1044e8f48>
Traceback (most recent call last):
File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/with_statement.py", line 32, in <module>
raise TypeError("TypeError inside with block")
TypeError: TypeError inside with block
If the __exit__() method returns True, then the exception is consumed and normal execution continues.
如果__exit __()方法返回True,则使用该异常并继续正常执行。
class MyContext:
def __init__(self):
print("init method of MyContext")
def __enter__(self):
print("entering context of MyContext")
def __exit__(self, exc_type, exc_val, exc_tb):
print(f'exit context of MyContext - {exc_type} :: {exc_val} :: {exc_tb}')
return True
with MyContext() as my_context:
print("my_context code")
raise TypeError("TypeError inside with block")
print("Done")
Output:
输出:
init method of MyContext
entering context of MyContext
my_context code
exit context of MyContext - <class 'TypeError'> :: TypeError inside with block :: <traceback object at 0x102149e08>
Done
(7. Conclusion)
Python with statement takes care of managing the life cycle of the context manager. The code looks small and removes the chance of leaving the context manager open due to poor programming.
Python with语句负责管理上下文管理器的生命周期。 该代码看起来很小,并且消除了由于不良编程而使上下文管理器保持打开状态的机会。
(8. References)
翻译自: https://www.journaldev.com/33273/python-with-statement-with-open-file
python打开文本文档