Reputation: 7
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 https://docs.python.org/3/library/functions.html#open). 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
Upvotes: 0
Views: 2250
Reputation: 263047
In Python, open() has two purposes:
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.
Upvotes: 2