Python File Access Modes
Python File Access Modes
In this tutorial, let’s learn about different file access modes supported by Python. Python provides various file access modes for opening files, which are used to specify the type of operations you intend to perform on the file.
The main operations on the file system can be CRUD operations. CRUD stands for
- Create
- Read
- Update
- Delete
Python File Access Modes
Numerous access modes are available to handle different types of file operations for an opened file. The main access modes supported in Python are as follows:
The file pointer, also known as the file handle, denotes the position from where data is to be read or written in a file.
File Access Mode |
Name | Description |
‘r’ | Read Only | This is the default mode. The read-only access mode is used to open the file for reading. The file handle/pointer is positioned at the beginning of the file( i.e. for the text file before the first character). If this file does not exist then it raises an I/O error. |
‘r+’ | Read and Write | The read-and-write access mode opens files for both reading and writing purposes. The file pointer is positioned at the beginning of the file. This mode also raises an I/O error if the file does not exist. |
‘w’ | Write Only | The write-only access mode is used to open the file for writing purposes only. For the existing file, the data is over-written. The file pointer is positioned at the beginning of the file. In this mode, the file is created if the file does not exist. |
‘w+’ | Write and Read | The write and read access mode opens the file for both writing and reading purposes. For the existing file, the data is over-written. The file pointer is positioned at the beginning of the file. |
‘a’ | Append Only | An append access mode opens the file for appending. In this mode, the file is created if this file does not exist. The file handle is positioned at the end of the file i.e. after the last character of the file. The data is inserted at the end, after the existing data in the file. |
‘a+’ | Append and Read | An append and read access mode opens the file for both reading and writing. The file is created if it does not exist. The file pointer is positioned at the end of the file. The written data will be inserted at the end, after the existing data in the file. |
It’s important to choose the correct file access mode for the file operations to avoid errors or unexpected behavior.
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: