We are now prepared to begin the topic of file handling techniques because we have a better understanding of what files (whether text or binary) are and how to access them. A file must first be opened before it can be read or written to, like on a hard disc. When we open a file, we ask the operating system to look for the file by name and confirm that it is present.

How can a file be opened?

A file can be opened in Python using the built-in open() function.

The function’s syntax is as follows:

open(“filename” ,”mode”)

Two conditions must be met in order to open a file:

The file’s name and extension

It is possible to indicate the access mode in which a file must be opened, such as read (r), write (w), append (a), etc.

For Example, 


The “rt” mode, which is the default mode, will be used to open the file “myfile.txt.” The ideal method, however, is to adhere to the syntax to prevent mistakes.

A file object is the result of the open function. We put this file object in a variable known as a file handler or file pointer. The following Python code snippet opens the file using file handling.

  f=open(“myfile.txt,” “w”)

This file pointer can be used to add more changes to the file. If the operation to open the file fails, an error may also be raised. It can be because you’re trying to read a file that’s open in write mode or you’re trying to access a closed file.

How can a file be read?

There are several ways to read a file in Python, including utilizing a for loop and iterator to read the entire file line by line. It will be quick and effective to read data in this manner.

Python requires precise instructions on how to open a file before it can read it. There are two access modes: reading (r) and reading in binary mode (rb). When using the built-in open() method to open a file, they must be supplied.

f = open(“myfile.txt”, “r”)

By default, the read() method reads the entire file. The read(size) method also allows us to define the number of characters we want to return, i.e.; #Here, you will get the first two characters of the file.

The readline() method can be used to read specific lines from a file. You can acquire the following line by using readline() once again.

The readlines() method reads the entire file, returning a list of its lines in the process. It only reads one line at a time.


f.readlines() #Returns a list object

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.