9.1 I/O handling functions

There are three built-in functions for I/O handling in Python, let's go through them one by one.

9.1.1 input(prompt) => None

Parameters:

  • >prompt Any: Your message to the screen.

Explanation: Reads input from standard input devices (such as keyboard) and takes it input as string.

9.1.2 print(*values, sep=' ', end='\n', file=sys.stdout, flush=False) => None

Parameters:

  • >values object: Takes the object to be printed, * indicates more than one object.
  • >sep Optional[str]: A separator between multiple values, default is a whitespace.
  • >end Optional[str]: The last print value, default is a newline.
  • >file Optional[Writer]: A file-like object (stream), default is screen.
  • >flush bool: Whether to forcibly flush the stream.

Explanation: Prints the given object to a standard output device, usually screen.

9.1.3 open(filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) => file

Parameters:

  • >filename Union[str, bytes]: String or byte path to a file.
  • >mode str: Opening file mode.
  • >buffering int: For specifying buffering policy.
  • >encoding Optional[str]: Specify encoding format. On Windows the default is "cp1252" and "utf-8" on Linux/OSX.
  • >errors Optional[str]: To handle Encoding/Decoding errors.
  • >newline Optional[str]: Specify how the newline works.
  • >closefd bool: If set to False, the underlying file descriptor will be kept open even when the file is closed.
  • >opener Optional[Callable[[str, int], int]]: A custom file opener, it should return a file descriptor.

Explanation: This function is used to open a file. It returns a file object (also called handle), this object is further used to perform operations such as read/write/append to a file. For different types of operations there are different modes available, default is "r" (reading).