Free cookie consent management tool by TermsFeed

Python - Input/Output operations

Overview:

A computer system provides various means for accepting input from users and delivering the output. For example, a file can be read from the file system and copied to a different location in the same file system. Input can be received from console or through a form in a graphical user interface or through a socket from a client computer.

Console input and output:

The console input and output is achieved through the built-in functions input() and print().

File I/O using the built-in function open():

In Python, input/output are performed in three modes: text, binary and raw. The open() function supports all the three modes. Based on the value of the parameter mode, the built-in function open() returns a specific type of file object to perform read and write operations.

The open() function returns an instance of _io.TextIOWrapper when opened in text mode. To open a file in text mode character “t” is to be added to the mode string. For example the function call open(“test.txt”, “tr”) opens a file for reading in text mode and returns a _io.TextIOWrapper object.

When opened in binary mode using the mode string “b” the open() function returns an instance of _io.BufferedReader.

For reading a file in raw mode the open() function needs be called with values mode=”rb” and buffering=0. In raw mode the open function returns an instance of _io.FileIO.

The actual contents can be read from or written to by calling the readln() and read() functions of the returned objects. 

Using the io module from the standard library:

The io module provides several abstract classes as the base interfaces for designing and implementing IO streams. It also provides concrete classes that handle IO operations.

Concrete classes handling IO:

The StringIO handles text input and output. The binary input and output operations are handled by the BytesIO class.

 

 


Copyright 2025 © pythontic.com