文件打开:这是坏的Python风格吗? [英] File open: Is this bad Python style?

查看:131
本文介绍了文件打开:这是坏的Python风格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要读取文件的内容:

data = open(filename, "r").read()

打开的文件立即停止在任何地方被引用,因此文件对象最终会关闭...,

The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.

编辑:这实际上是在我写的一个项目中咬我了 - 它提示我要求问题。仅当内存不足时才清除文件对象,而不是在文件句柄耗尽时清除。因此,如果你这样做太频繁,你可能会导致文件描述符,并导致你的IO尝试打开文件时抛出异常。

This has actually bitten me in a project I wrote - it prompted me to ask this question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.

推荐答案

只是为了记录:
这只是稍长,并立即关闭文件:

Just for the record: This is only slightly longer, and closes the file immediately:

from __future__ import with_statement

with open(filename, "r") as f:
    data = f.read()

这篇关于文件打开:这是坏的Python风格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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