Understand using Python Open, Read, Write methods with 2 Demos

The open method of Python

Python comes up with a built-in function open() that enables programmers to perform open, read, write and other operations with files.

>>An example of Open and read file

In order to perform the read or write actions in the files, first, it has to be opened. Once a file is opened by using the python open() method, that creates a file object. After that, associated actions can be performed on those file(s).

Syntax of open() method

Following is the syntax of open file method:

File_object = open(file_path [, access mode] [, buffer])

Where

  • file_path is the path of the file to be opened.
  • Access mode defines the mode of file – read, write, append etc. This is an optional parameter. The ‘r’ is the default mode. See the last part of this tutorial for access mode parameters and its descriptions.
  • If buffer value is set to 0, no buffering will take place. If the value is set to 1 line, buffering will be performed.

Example of open and read file

The following example will open a text file, located on the same directory where the source file is located. The program will open the file, read by using Python read file method and print the text of the test.txt file.

For that, suppose test.txt contains:

“This is open file method!

The example shows open and python read the file.”

See this example online

The output will be:

Python open method

 

Python write to file example

The following example shows how to use the write to file method in Python. For this example, suppose test.txt file is empty, which is placed at the same location where Python code file resides.

First of all, the write to file step will occur where we will use the open and write methods.

After that, the file will be closed by using the close method.

Once again, the open() method will be used to open and read the file and print the written text by using the read file method.

See this example online

The output will be:

The file contains:  This is Python open file method!

The example shows open and write to file.

The file open Access modes

As shown in the syntax of the open method, you can use Access mode to define the desired action with the file. Access modes with the short description are listed below:

  • r = opens the file as read-only.
  • rb = Read only and in binary format
  • w = write-only mode
  • wb = write only in binary format
  • r+ = read and write mode
  • rb+ = read and write in binary mode
  • a = opens the file in append mode. If the file exists the pointer goes at the end.
  • ab = file in append and binary mode
  • a+ = append and read mode
  • ab+ = append and read in binary mode

 

Further Reading: Python user input