In projects, you are often required to read data from a file or write data to a file. Python provides inbuilt functions for handling read/write operations on files. In this tutorial, you'll learn how to read/write a file. Let's get started.
Before you read or write a file, you'll need to open a file first. The in-built method open() is used to open a file. It will create a file object which will provide you methods to read or write a file.
Let's look at the syntax of open() method.
file_object = open( r'file_name', 'access_mode')
As you can see here, it has 2 parameters:
- file_name — the name of the file that you want to access.
- access_mode — specifies the type of access you want for a file. Default access mode is r (reading only). Some other access modes are w (writing only), a (appending only), r+ (reading and writing both), etc.
Important : In the given syntax, r is for raw string. It enables Python interpreter to read file path correctly. For example, if we do not use r before the file path and path includes \temp then Python will interpret \t as special tab character, thereby raising an error. So, use r before the file name if it includes full path to avoid errors.
Do not forget to close the file after your done reading/writing to it. This is done with the close() method.