是否需要关闭没有引用的文件? [英] Is there a need to close files that have no reference to them?

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

问题描述

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

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术语中的 system调用)所提供的魔力.隐藏在文件对象内部的是对文件描述符"的引用,文件描述符"是与打开的文件关联的实际OS资源.关闭文件会告诉系统释放该资源.

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语句打开文件.当到达with块的末尾时,即使在异常终止(由于异常)的情况下,也会调用close()方法.

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天全站免登陆