如何关闭我从未分配给变量的文件对象? [英] How do I close a file object I never assigned to a variable?

查看:142
本文介绍了如何关闭我从未分配给变量的文件对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(打开(原点)),从sys导入 argv
脚本,origin,destination = argv

open(destination,'w' .read())

如何关闭目标文件和原始文件对象?或者这是我不需要担心的事情?

解决方案

简而言之,您不应该担心这些问题,但在更大的程序中,可能会耗尽文件描述符。



从2.5版本开始,Python有语句,它可以为您关闭文件:

  from __future__ import with_statement#只有Python 2.5 
开放(destination,'w')作为dest:
开放(origin)作为orig:
dest .write(orig.read())


from sys import argv
script, origin, destination = argv

open(destination, 'w').write(open(origin).read())

How do I close the destination and origin file objects? Or is this something I don't need to worry about?

解决方案

In short straightforward scripts you shouldn't worry about these issues, but in bigger programs you might run out of file descriptors.

Since version 2.5, Python has with statement, which can do the file closing for you:

from __future__ import with_statement # Only required for Python 2.5
with open(destination, 'w') as dest:
   with open(origin) as orig:
        dest.write(orig.read())

这篇关于如何关闭我从未分配给变量的文件对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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