eersoy93 eersoy93 - 1 year ago 78
Python Question

Why a filename is given closefd parameter of open() Function must be True in Python 3.5.2?

In Python 3.5.2, when I give False value to closefd parameter of open() function with a filename, I get this error below:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Cannot use closefd=False with file name

Results for me of my question (Why a filename is given closefd of open() Function must be True in Python 3.5.2?) and queries similiar to my question (e.g. closefd parameter in python) in Google Search isn't satisfying, the link of the results is below (You will may get different results.):

In Python 3.5.2 documentation, there is only a description for closefd parameter of open() function (The link of open() function in Python 3.5.2 documentation is The description is below:

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.

I couldn't find the answer of this question. My Python version string that first outputted in my Python command line interpreter is below:

Python 3.5.2 (default, Jul 5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux

Answer Source

In Python, open() has two purposes:

  1. To open a given file from its name, or
  2. To wrap a file descriptor representing an already open file.

The second purpose is useful if you have a file descriptor and you want to use portable Python functions (rather than the os module) to manipulate it. However, in that case, the file descriptor will be closed when the Python file object wrapper is closed, which you may not want (as you may want the file descriptor to remain valid for further uses).

Therefore, the open() function provides an argument that allows you to specify you want the file descriptor to remain open. Since this behavior only makes sense when you pass a file descriptor to open(), an error is raised if you try to use it in conjunction with a file name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download