Opening and reading files in python

Opening Files with open()

This function returns a file object called “handle”, which is used to read from and write to a file. The arguments that the function can receive are as follows:

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

Normally, only the filename and mode parameters are needed, while the others are used implicitly set with their default values.

The following code snippet shows how this function can be used:

file_example = open ("TestingText.txt")

This will open a text file called “TestingText” in read-only mode. Take note that only the filename parameter was specified, this is due to the “read” mode being the default mode for the open function.

The access modes available for the open() function are as follows:

  • r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.
  • rb: Opens the file as read-only in binary format and starts reading from the beginning of the file. While binary format can be used for different purposes, it is usually used when dealing with things like images, videos, etc.
  • r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
  • w: Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn’t exist.
  • wb: Opens a write-only file in binary mode.
  • w+: Opens a file for writing and reading.
  • wb+: Opens a file for writing and reading in binary mode.
  • a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn’t exist.
  • ab: Opens a file for appending in binary mode.
  • a+: Opens a file for both appending and reading.
  • ab+: Opens a file for both appending and reading in binary mode.

source: stackabuse

Related