使用“与” Python 中 CSV 文件的语句
是否可以直接对 CSV 文件使用 with
语句? 能够执行这样的操作似乎很自然:
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 语句兼容?
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
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
Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
with
语句的主要用途是对语句中使用的对象进行异常安全清理。with
确保文件已关闭、锁已释放、上下文已恢复等。csv.reader 有异常情况需要清理吗?
我会选择:
您不需要提交补丁即可一起使用
csv.reader
和with
语句。模块 contextlib 中函数 contextmanager 的帮助:
典型用法:
这使得此:
相当于此:
这是我如何使用它的具体示例: 诅咒屏幕。
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.Does csv.reader have things to cleanup in case of exception?
I'd go with:
You don't need to submit the patch to use
csv.reader
andwith
statement together.Help on function contextmanager in module contextlib:
Typical usage:
This makes this:
equivalent to this:
Here's a concrete example how I've used it: curses_screen.
是的。 第二种方法是正确的。
至于为什么? 谁知道呢。 你是对的,这可能是一个简单的改变。 它不像其他事情那么优先。
您可以轻松制作自己的补丁包并提交。
Yes. The second way is correct.
As to why? Who ever knows. You're right, it's probably an easy change. It's not as high priority as other things.
You can easily make your own patch kit and submit it.
问题是 csv.reader 并没有真正管理上下文。 它可以接受任何可迭代对象,而不仅仅是文件。 因此,它不会对其输入调用 close (顺便说一句,如果这样做,您可以使用 contextlib. opening )。 因此,对 csv.reader 的上下文支持实际上会做什么并不明显。
The problem is csv.reader doesn't really manage a context. It can accept any iterable, not just a file. Therefore it doesn't call close on its input (incidentally if it did you could use contextlib.closing). So it's not obvious what context support for csv.reader would actually do.
使用生成器函数可以轻松创建您想要的内容:
It's easy to create what you want using a generator function:
正如其他答案所指出的,第二种方法是更好的选择。 而且我认为 FileContextHandle 将来不会出现,因为 csv 模块估计的是 Iterator[str],而不是 Typing.IO。
然而,缺少提供完整功能和正确文件上下文处理的 csv_open。
As pointed out by other answers, the second way is the better option. And I think that a FileContextHandle will not come in the future, because the csv-module estimates Iterator[str], not typing.IO.
However there is a lack for a csv_open, that provides full functionality and correct file-context-handling.