对Python中的CSV文件使用“with”语句

栏目: Python · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/441130/using-with-statement-for-csv-files-in-python

是否可以直接使用with语句与CSV文件?能够做这样的事情似乎很自然:

import csv
with csv.reader(open("myfile.csv")) as reader:
    # do things with reader

但是csv.reader不提供__enter__和__exit__方法,所以这不行.但是我可以分两步做:

import csv
with open("myfile.csv") as f:
    reader = csv.reader(f)
    # do things with reader

这是第二种方式吗?为什么他们不会使csv.reader与with语句直接兼容?

with语句的主要用法是对语句中使用的对象进行异常安全的清除.确保文件已关闭,锁定已释放,上下文恢复等.

Python .org/library/csv.html#csv.reader” rel=”noreferrer”>csv.reader是否有异常清理的东西?

我会一起去:

with open("myfile.csv") as f:
    for row in csv.reader(f):
        # process row

您不需要将修补程序提交到一起使用csv.reader和语句.

import contextlib

模块 contextlib 中功能上下文管理器的帮助:

contextmanager(func)
    @contextmanager decorator.

典型用法:

@contextmanager
    def some_generator(<arguments>):
        <setup>
        try:
            yield <value>
        finally:
            <cleanup>

这使得:

with some_generator(<arguments>) as <variable>:
        <body>

相当于:

<setup>
    try:
        <variable> = <value>
        <body>
    finally:
        <cleanup>

以下是我如何使用它的具体示例: curses_screen .

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/441130/using-with-statement-for-csv-files-in-python


以上所述就是小编给大家介绍的《对Python中的CSV文件使用“with”语句》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Test Driven Development

Test Driven Development

Kent Beck / Addison-Wesley Professional / 2002-11-18 / USD 49.99

Quite simply, test-driven development is meant to eliminate fear in application development. While some fear is healthy (often viewed as a conscience that tells programmers to "be careful!"), the auth......一起来看看 《Test Driven Development》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具