Open | Difference Between Modes a, a+, w, w+, And r+ In Built-in Open Function?

In this tutorial, we will find the Difference between modes a, a+, w, w+, and r+ in the built-in open function which gives a way to read and write into a file of python along with some of the arguments of it helps in generating the output as per our choice. And here we will explore each of them one by one.

 

open

Open

It is an in-built function that is used for opening, reading, and writing the test in the file stored in the local machine and there are different modes for it that we will discuss here one by one.

‘r’

It is used for opening the file and reading only, and if the file does not exist then it would give an error as fileNotFound error when an exception is raised. For the same, we have an example given below which we are going to discuss here.

# Open a file for reading
with open(' example.txt', 'r') as f:
    data = f.read()
    print( data)

It will open the file.

‘r+’

As the name indicate it is used when we need to read and write we required both the reading as well as writing so, in that case, we use r+ mode to open the file, for the same follow the example given below.

# Open a file for reading and writing
with open(' example.txt', 'r+') as f:
    data = f.read()
    f.write(' Hello, world!')

‘w’

It is used when we only have to write into the file we can only write in this mode for example:

# Open a file for writing (truncate if file exists)
with open(' example.txt', 'w') as f:
    f.write(' Hello, world!')

‘w+’

It is the same ad r+ where we can read and write both can be done by one simple mode for example look at the example given below:

# Open a file for reading and writing (truncate if file exists)
with open(' example.txt', 'w+') as f:
    f.write(' Hello, world!')
    f.seek(0)  # Move the file pointer to the beginning of the file
    data = f.read()
    print( data)

‘a’

As the name indicates ‘a’ is used to simply append the text in existing text in the file for completing it the following example:

# Open a file for appending
with open(' example.txt', 'a') as f:
    f.write(' Hello, world!')

‘a+’

As the name indicate it is used for reading and the append the text to the file in the example.

# Open a file for reading and appending
with open(' example.txt', 'a+') as f:
    f.write(' Hello, world!')
    f.seek(0)  # Move the file pointer to the beginning of the file
    data = f.read()
    print( data)

 

To learn more about opening and reading, writing and appending the text in an existing file using python visit: Open function

To learn more about python visit: Python Tutorials And Problems.

 

 

 

Leave a Comment

%d bloggers like this: