I realised that the open()
function I've been using was an alias to io.open()
and that importing *
from os
would overshadow that.
What's the difference between opening files through the io
module and os
module?
io.open()
is the preferred, higher-level interface to file I/O. It wraps the OS-level file descriptor in an object that you can use to access the file in a Pythonic manner.
os.open()
is just a wrapper for the lower-level POSIX syscall. It takes less symbolic (and more POSIX-y) arguments, and returns the file descriptor (a number) that represents the opened file. It does not return a file object; the returned value will not have read()
or write()
methods.
From the os.open()
documentation:
This function is intended for low-level I/O. For normal usage, use the built-in function
open()
, which returns a “file object” withread()
andwrite()
methods (and many more).
Although I have to wonder, why would anyone choose Python for low-level I/O?
Maybe Python is the language in which the coder is the most comfortable. Or maybe they are writing an addon for another Python program.
Why not? Low-level manipulation doesn't dictate in what language it should we expressed.
My point is that you do want to write low-level code in Python, among other, high-level code, to which Python is more suited.
@cdhowie that's a false dichotomy. You might want to use Python AND perform low level control of the system. It's also wrong that "not doing so results in less portable, less readable, and less maintainable code". Compared to what? Talking to the same low level APIs in C? No, it will be more portable and readable to talk to them from Python. If you mean "compared to using high level interfaces" that's a moot point, if what you need to do (business goal) involves low level interfaces. Low/High level APIs != Low/High level languages.