是否需要关闭与它们无关的文件? [英] Is there a need to close files that have no reference to them?

查看:23
本文介绍了是否需要关闭与它们无关的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个完整的编程初学者,我试图理解打开和关闭文件的基本概念.我正在做的一个练习是创建一个脚本,允许我将内容从一个文件复制到另一个文件.

As a complete beginner to programming, I am trying to understand the basic concepts of opening and closing files. One exercise I am doing is creating a script that allows me to copy the contents from one file to another.

in_file = open(from_file)
indata = in_file.read()

out_file = open(to_file, 'w')
out_file.write(indata)

out_file.close()
in_file.close()

我试图缩短这段代码并想出了这个:

I have tried to shorten this code and came up with this:

indata = open(from_file).read()
open(to_file, 'w').write(indata)

这有效,对我来说看起来更有效率.然而,这也是我感到困惑的地方.我想我省略了对打开文件的引用;不需要 in_file 和 out_file 变量.但是,这是否给我留下了两个打开的文件,但没有任何涉及它们的内容?我如何关闭这些,或者不需要?

This works and looks a bit more efficient to me. However, this is also where I get confused. I think I left out the references to the opened files; there was no need for the in_file and out_file variables. However, does this leave me with two files that are open, but have nothing referring to them? How do I close these, or is there no need to?

非常感谢任何对这个主题有所了解的帮助.

Any help that sheds some light on this topic is much appreciated.

推荐答案

您询问了基本概念",所以让我们从顶部开始:当您打开文件时,您的程序可以访问系统资源,也就是程序自身内存空间之外的东西.这基本上是操作系统提供的一些魔法(系统调用, 在 Unix 术语中).隐藏在文件对象中的是对文件描述符"的引用,即与打开的文件相关联的实际操作系统资源.关闭文件告诉系统释放这个资源.

You asked about the "basic concepts", so let's take it from the top: When you open a file, your program gains access to a system resource, that is, to something outside the program's own memory space. This is basically a bit of magic provided by the operating system (a system call, in Unix terminology). Hidden inside the file object is a reference to a "file descriptor", the actual OS resource associated with the open file. Closing the file tells the system to release this resource.

作为操作系统资源,进程可以保持打开的文件数量是有限的:很久以前,Unix 上的每个进程限制约为 20.现在,我的 OS X 机器限制了 256 个打开的文件(尽管这是一个强加的限制,可以提高).其他系统可能会设置几千的限制,或者在数万(在这种情况下,每个用户,而不是每个进程).当您的程序结束时,所有资源都会自动释放.因此,如果您的程序打开了几个文件,对它们进行了一些操作并退出,您可能会草率且永远不会知道其中的区别.但是,如果您的程序将打开数千个文件,则最好释放打开的文件以避免超出操作系统限制.

As an OS resource, the number of files a process can keep open is limited: Long ago the per-process limit was about 20 on Unix. Right now my OS X box imposes a limit of 256 open files (though this is an imposed limit, and can be raised). Other systems might set limits of a few thousand, or in the tens of thousands (per user, not per process in this case). When your program ends, all resources are automatically released. So if your program opens a few files, does something with them and exits, you can be sloppy and you'll never know the difference. But if your program will be opening thousands of files, you'll do well to release open files to avoid exceeding OS limits.

在进程退出之前关闭文件还有另一个好处:如果您打开一个文件进行写入,关闭它将首先刷新其输出缓冲区".这意味着 i/o 库优化了磁盘使用通过收集(缓冲")您写出的内容,并将其分批保存到磁盘.如果您将文本写入文件并立即尝试重新打开并读取它而不先关闭输出句柄,您会发现并非所有内容都已写出.此外,如果您的程序关闭得太突然(有信号,或者偶尔甚至通过正常退出),输出可能永远不会被刷新.

There's another benefit to closing files before your process exits: If you opened a file for writing, closing it will first "flush its output buffer". This means that i/o libraries optimize disk use by collecting ("buffering") what you write out, and saving it to disk in batches. If you write text to a file and immediately try to reopen and read it without first closing the output handle, you'll find that not everything has been written out. Also, if your program is closed too abruptly (with a signal, or occasionally even through normal exit), the output might never be flushed.

关于如何发布文件已经有很多其他的答案,所以这里只是简单的方法列表:

There's already plenty of other answers on how to release files, so here's just a brief list of the approaches:

  1. 明确地使用 close().(python 新手注意:不要忘记括号!我的学生喜欢写 in_file.close,它什么都不做.)

  1. Explicitly with close(). (Note for python newbies: Don't forget the parens! My students like to write in_file.close, which does nothing.)

推荐:隐式地,通过使用 with 语句打开文件.close() 方法将在到达 with 块的末尾时被调用,即使在异常终止(来自异常)的情况下也是如此.

Recommended: Implicitly, by opening files with the with statement. The close() method will be called when the end of the with block is reached, even in the event of abnormal termination (from an exception).

with open("data.txt") as in_file:
    data = in_file.read()

  • 由引用管理器或垃圾收集器隐式执行,如果您的 Python 引擎实现了它.不推荐这样做,因为它不是完全可移植的;有关详细信息,请参阅其他答案.这就是为什么将 with 语句添加到 python 中的原因.

  • Implicitly by the reference manager or garbage collector, if your python engine implements it. This is not recommended since it's not entirely portable; see the other answers for details. That's why the with statement was added to python.

    隐含地,当您的程序结束时.如果打开文件进行输出,则可能会存在程序在所有内容刷新到磁盘之前退出的风险.

    Implicitly, when your program ends. If a file is open for output, this may run a risk of the program exiting before everything has been flushed to disk.

    这篇关于是否需要关闭与它们无关的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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