In Python, the file mode specifies the purpose and the operations that can be performed on a file when it is opened. When you open a file using the open() function, you can specify the file mode as the second argument.
Different File Mode in Python
Below are the different types of file modes in Python along with their description:
Mode
| Description
|
---|
‘r’ | Open text file for reading. Raises an I/O error if the file does not exist. |
‘r+’ | Open the file for reading and writing. Raises an I/O error if the file does not exist. |
‘w’ | Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘w+’ | Open the file for reading and writing. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘a’ | Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist. |
‘a+’ | Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist. |
‘rb’ | Open the file for reading in binary format. Raises an I/O error if the file does not exist. |
‘rb+’ | Open the file for reading and writing in binary format. Raises an I/O error if the file does not exist. |
‘wb’ | Open the file for writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘wb+’ | Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist. |
‘ab’ | Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist. |
‘ab+’ | Open the file for reading and appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist. |
File Mode in Python
Below are some of the file modes in Python:
Read Mode ('r') in Python
This mode allows you to open a file for reading only. If the file does not exist, it will raise a FileNotFoundError.
example.txt
Hello Geeks
Example:
In this example, a file named 'example.txt' is opened in read mode ('r'), and its content is read and stored in the variable 'content' using a 'with' statement, ensuring proper resource management by automatically closing the file after use.
Python3
with open('example.txt', 'r') as file:
content = file.read()
Output:
Hello Geeks
Write Mode ('w') in Python
This mode allows you to open a file for writing only. If the file already exists, it will truncate the file to zero length. If the file does not exist, it will create a new file.
example.txt
Hello, world!
Example:
In this example, a file named 'example.txt' is opened in write mode ('w'), and the string 'Hello, world!' is written into the file.
Python3
with open('example.txt', 'w') as file:
file.write('Hello, world!')
Output:
Hello, world!
Note - If you were to open the file "example.txt" after running this code, you would find that it contains the text "Hello, world!".
Append Mode ('a') in Python
This mode allows you to open a file for appending new content. If the file already exists, the new content will be added to the end of the file. If the file does not exist, it will create a new file.
example.txt
Hello, World!
This is a new line
Example:
In this example, a file named 'example.txt' is opened in append mode ('a'), and the string '\nThis is a new line.' is written to the end of the file.
Python3
with open('example.txt', 'a') as file:
file.write('\nThis is a new line.')
Output:
Hello, World!
This is a new line
The code will then write the string "\nThis is a new line." to the file, appending it to the existing content or creating a new line if the file is empty.
Binary Mode ('b') in Python
This mode use in binary files, such as images, audio files etc. Its always used by combined with read (`'rb'`) or write ('wb') modes.
Example:
In this example, a file named 'image.png' is opened in binary read mode ('rb'). The binary data is read from the file using the 'read()' method and stored in the variable 'data'.
Python3
with open('image.png', 'rb') as file:
data = file.read()
# Process the binary data
Read and Write Mode ('r+') in Python
This mode allows you to open a file for both reading and writing. The file pointer will be positioned at the beginning of the file. If the file does not exist, it will raise a FileNotFoundError.
example.txt
This is a new line.
Initial content.
Python3
with open('example.txt', 'r+') as file:
content = file.read()
file.write('\nThis is a new line.')
Output:
If the initial contents of "example.txt" we are "Initial content.", after running this code, the new content of the file would be:
This is a new line.
Initial content.
Write and Read Mode ('w+') in Python
This mode allows you to open a file for both reading and writing. If the file already exists, it will truncate the file to zero length. If the file does not exist, it will create a new file.
example.txt
Hello, world!
Example:
In this example, a file named 'example.txt' is opened in write and read mode ('w+').
Python3
with open('example.txt', 'w+') as file:
file.write('Hello, world!')
file.seek(0)
content = file.read()
Output:
Therefore, the output of this code will be the string "Hello, world!". Since the file was truncated and the pointer was moved to the beginning before reading, the contents of the file will be exactly what was written to it. So, content will contain the string "Hello, world!".
Hello, world!
Similar Reads
Open a File in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, each line of text is terminated with a special character called EOL
6 min read
File Objects in Python
A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files. When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek()
6 min read
in_place module in Python
Sometimes, while working with Python files, we can have utility in which we wish to alter files without using system context or sys stdout. Such situation require reading/writing files inplace, i.e without using process resources. This can be achieved using the ein_place module in Python. This modul
3 min read
HDF5 files in Python
HDF5 file stands for Hierarchical Data Format 5. It is an open-source file which comes in handy to store large amount of data. As the name suggests, it stores data in a hierarchical structure within a single file. So if we want to quickly access a particular part of the file rather than the whole fi
5 min read
File Handling in Python
File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
7 min read
Parse a YAML file in Python
YAML is the abbreviation of Yet Another Markup Language or YAML ain't markup Language which is the data format used to exchange data. YAML can store only data and no commands. It is similar to the XML and JSON data formats. In this article, we will dive deep into the concept of parsing YAML files in
4 min read
Setting file offsets in Python
Prerequisite: seek(), tell() Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer
4 min read
fileinput.input() in Python
With the help of fileinput.input() method, we can get the file as input and can be used to update and append the data in the file by using fileinput.input() method. Python fileinput.input() Syntax Syntax : fileinput.input(files) Parameter : fileinput module in Python has input() for reading from mul
2 min read
json.load() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Pytho
3 min read
Python: filecmp.cmp() method
Filecmp module in Python provides functions to compare files and directories. This module comes under Pythonâs standard utility modules. This module also consider the properties of files and directories for comparison in addition to data in them. filecmp.cmp() method in Python is used to compare two
3 min read