简体   繁体   English

python中的'with'函数有什么作用?

[英]what does the 'with' function in python do?

I have a python script that reads in a .csv file that works fine for Python 2.7 but is breaking on Python 2.4. 我有一个python脚本,读取.csv文件,适用于Python 2.7,但在Python 2.4上打破。 The error being thrown is on the line 抛出的错误就行了

with open(sys.argv[1], 'rb') as csvfile:

Right here it's giving me a syntax error so my question is what does 'with' do (or whatever part of this could throw a syntax error in 2.4). 就在这里,它给了我一个语法错误,所以我的问题是'与'做什么(或者这可能会导致2.4中的语法错误)。 I can't find documentation on this function anywhere, partly because of its generic name. 我无法在任何地方找到关于此功能的文档,部分原因是它的通用名称。

You are looking at a context manager; 您正在查看上下文管理器; for relevant documentation that is an easier term to search on. 相关文档,这是一个更容易搜索的术语。

  • The original proposal PEP-343 to add the feature describes context managers in detail. 添加该功能的原始提议PEP-343详细描述了上下文管理器。

  • The datamodel documentation describes what makes a context manager. datamodel文档描述了上下文管理器的用途 Context managers have .__enter__() and .__exit__() methods. 上下文管理器有.__enter__().__exit__()方法。

  • The with statement itself is documented as a compound statement in the reference documentation. with语句本身在参考文档中记录为复合语句

  • For file objects, the File object documentation (part of the standard types documentation) describes that most file objects can be used as context managers. 对于文件对象, File对象文档(标准类型文档的一部分)描述了大多数文件对象可以用作上下文管理器。

For files specifically, the relevant part you were looking for is documented with the file.close() method , because that is what the context manager .__exit__() method does for files: close the files whatever else happened. 具体来说,对于文件,您要查找的相关部分是使用file.close()方法记录的 ,因为这是上下文管理器.__exit__()方法对文件的作用:关闭文件,无论发生什么。

Translating that to older Python versions where there is no support for the with statement yet, that means you have to manually close your file, with a try: finally: combination: 将其转换为不支持with语句的旧Python版本,这意味着您必须手动关闭文件,使用try: finally:组合:

csvfile = open(sys.argv[1], 'rb')
try:

    # do things with csvfile

finally:
    csvfile.close()

This ensures that csvfile is properly closed whatever else happens. 这可确保csvfile在其他任何情况下正确关闭。

In the concrete case of opening a file, it achieves the following: 在打开文件的具体情况下,它实现了以下功能:

cvsfile = open(sys.argv[1], 'rb')
try:
   ...
finally:
    cvsfile.close()

Python 2.5 and later allow objects used as expressions in with ( context managers ) to define how they enter the context and leave it. 的Python 2.5和更高版本允许使用表达式中的对象with上下文管理器 )来定义它们是如何进入的背景下,离开它。 Files will be closed when leaving with , locks will be unlocked, and so on. 离开时,文件将被关闭with ,锁将被解锁,等等。

PEP 343 that introduced with is still quite an informative read. PEP 343介绍了with仍然是一个相当有价值的信息读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM