This is because open() is a function, and .close() is an object method. "file".open() does not make sense, because you mean that the open() function is actually a class method or an instance of the string "file" . Not all lines are valid files or devices that should be opened, so the way the interpreter should handle "not a file-like device".open() will be ambiguous. We do not use "file".close() for the same reason.
close("file") will require a file name search and then another search to see if there are any files belonging to the current process attached to this file. This would be very inefficient and probably there would be hidden traps that would make it unreliable (for example, what if it is not a file, but a TTY device instead?). It is much simpler and easier to simply reference an open file or device and close the file through this link (also called a descriptor).
Many languages use this approach:
f = open("file")
This is similar to your close("file") constructor, but don't be fooled by it: it closes the file using a direct link to it, and not the file name stored in the string.
The Python developers decided to do the same, but they look different because instead they implemented it with an object-oriented approach. This is partly due to the fact that many file methods are available for Python file objects, read() , flush() , seek() , etc. If we used close(f) , we would either have to change all the other methods of the file object to functions, or allow it to be one random function that behaves differently from the rest for no good reason.
TL; DR
The open() and file.close() consistent with OOP principles and good file practice. open() is a factory-like function that creates objects that reference files or other devices. After creating an object, all other operations on this object are performed using the methods of the class or instance.
skrrgwasme
source share