Tuesday, 21 September 2021

Python: file access 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

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment