Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between io.open() and os.open() on Python?

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?

like image 525
Gio Borje Avatar asked Aug 28 '11 07:08

Gio Borje


People also ask

What is io Open in Python?

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.

What does io open() do?

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.

What is the difference between open and with open in python?

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.

What does with open do in Python?

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.


2 Answers

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” with read() and write() methods (and many more).

like image 90
cdhowie Avatar answered Oct 09 '22 10:10

cdhowie


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.

like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 09 '22 10:10

Ignacio Vazquez-Abrams