使用“与”在Python中的CSV文件的语句 [英] Using "with" statement for CSV files in Python

查看:111
本文介绍了使用“与”在Python中的CSV文件的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以直接使用语句与CSV文件?看起来自然能够做这样的事情:

Is it possible to use the with statement directly with CSV files? It seems natural to be able to do something like this:

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

但是csv。阅读器不提供 __ enter __ __ exit __ 方法,因此这不工作。我可以通过两个步骤:

But csv.reader doesn't provide the __enter__ and __exit__ methods, so this doesn't work. I can however do it in two steps:

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

这是第二种方式的理想方式吗?为什么不让csv.reader与with语句直接兼容?

Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?

推荐答案

with 语句是语句中使用的对象的异常安全清除。 使用确保文件关闭,锁定被释放,上下文被恢复等。

The primary use of with statement is an exception-safe cleanup of an object used in the statement. with makes sure that files are closed, locks are released, contexts are restored, etc.

=http://docs.python.org/library/csv.html#csv.reader =noreferrer> csv.reader 在异常情况下需要清理吗?

Does csv.reader have things to cleanup in case of exception?

我会用:

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

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

You don't need to submit the patch to use csv.reader and with statement together.

import contextlib

帮助 contextlib 模块中的函数contextmanager:

Help on function contextmanager in module 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

Here's a concrete example how I've used it: curses_screen.

这篇关于使用“与”在Python中的CSV文件的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆