Tuesday 21 September 2021

Python: r+ and w+ modes

 

Python come up with different access modes, that help while performing read and write operations with files. Below table summarizes different access modes.

        

Access Mode

Description

r

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. 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.

w

Write only mode. This mode is used to write the content to a file. It creates a file, if the file is not exist.

w+

Read and write mode. Open the file to perform both read and write operations. This mode either creates a file or truncates the existing file.

a

Append only mode. Open the file for appending content. It creates a file, if the file is not exist.

 

That data written to the file is appended to the end.

a+

Append and read mode. It creates a file, if the file is not exist. That data written to the file is appended to the end.

        

 

Below table summarizes different operations performed by these access modes.

 

Operation

r

r+

w

w+

a

a+

Read

Yes

Yes

 

Yes

 

Yes

Write

 

Yes

Yes

Yes

Yes

Yes

Create

 

 

Yes

Yes

Yes

Yes

Truncate

 

 

Yes

Yes

 

 

Handle position at start

Yes

Yes

Yes

Yes

 

 

Handle position at end

 

 

 

 

Yes

Yes

 

 

Difference between r+ and w+ modes

a.   If the file does not exist, r+ mode raise FileNotFoundError and w+ creates the file.

b.   If the file exists, r+ opens it without truncating and w+ truncates the file and opens it.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment