Tuesday, 21 September 2021

Python: r vs r+ mode

r : Read only mode

Read only mode. Open a file for reading. It is the default mode, by any chance if the file is not exists, this method raise I/O error.

 

When you open a file using this mode, file handle is positioned at the beginning of the file.

 

r+ : read and write mode

Read and write mode. Open the file to perform both read and write operations. By any chance if the file is not exists, this method raise I/O error.

 

This mode opens an existing file without truncating it.

 

Below table summarizes different operations performed by these access modes.

 

Operation

r

r+

Read

Yes

Yes

Write

 

Yes

Create

 

 

Truncate

 

 

Handle position at start

Yes

Yes

Handle position at end

 

 

 

Let’s see it with an example.

 

hello.txt

Hello World
Welcome to the world

 

read_mode_1.py

import os

file_to_read = 'hello.txt'
path = "/Users/Shared/data"

with open(os.path.join(path, file_to_read), 'r') as fp:
    lines = fp.readlines()      
    print(lines)

Output

['Hello World\n', 'Welcome to the world\n']

Let’s read and write some content to hello.txt file.

 

read_plus_mode_1.py

import os

file_to_check = 'hello.txt'
path = "/Users/Shared/data"

with open(os.path.join(path, file_to_check), 'r+') as fp:
    lines = fp.readlines() 
    print(lines)

    print("\nWriting some content to the file\n")

    # Placing the file handle to start
    fp.seek(0)
    fp.write("test 1\n")

    # Placing the file handle to start
    fp.seek(0)
    lines = fp.readlines()
    print(lines)

Output

['Hello World\n', 'Welcome to the world\n']

Writing some content to the file

['test 1\n', 'orld\n', 'Welcome to the world\n']



 

Previous                                                    Next                                                    Home

No comments:

Post a Comment