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?
The io module provides Python's main facilities for dealing with various types of I/O. There are three main types of I/O: text I/O, binary I/O and raw I/O. These are generic categories, and various backing stores can be used for each of them.
The io. open() function is a much preferred way to perform I/O operations as it is made as a high-level interface to peform file I/O. It wraps the OS-level file descriptor in an object which we can use to access the file in a Pythonic way.
Part 1: The Difference Between open and with open Basically, using with just ensures that you don't forget to close() the file, making it safer/preventing memory issues.
with statements open a resource and guarantee that the resource will be closed when the with block completes, regardless of how the block completes. Consider a file: with open('/etc/passwd', 'r') as f: print f.
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).
Absolutely everything:
os.open()
takes a filename as a string, the file mode as a bitwise mask of attributes, and an optional argument that describes the file permission bits, and returns a file descriptor as an integer.
io.open()
takes a filename as a string or a file descriptor as an integer, the file mode as a string, and optional arguments that describe the file encoding, buffering used, how encoding errors and newlines are handled, and if the underlying FD is closed when the file is closed, and returns some descendant of io.IOBase
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With