Python | Working with Files | Open and Read a Text File

We need to create a text file that we will work with. So, create a text file and call it example.txt and type in about three lines of sample text.

This is the first line
This is the second line
This is the third line

In Python, the command for opening a file is open(‘name_of_the_file’,’file_module’).

The first parameter is the path to the file you want to open. If it is in the same directory as the program then you just type in the name of the file.

The second parameter is for the file mode we want to open the file in. We have many options here but here you have a few of them:

r mode – It opens the file in read-only mode.
w mode – It opens the file in write-mode for only writing to it. If the file doesn’t exist, it will be created. If the file exist then all the data WILL BE erased.
a – It opens the file in append-mode for appending data at the end of the file. If the file doesn’t exist then it will be created. If the file exists then the data WILL NOT be erased.
r+ – It opens the file in both read and write mode.

Let’s take a look at the following example:

variableOne = open('example.txt','r')

firstLine = variableOne.readline()
secondLine = variableOne.readline()



The file example.txt is just a simple text file with three lines of text.
If you run the code in terminal then this is what you get.

Python open a file in r mode

The first line opens the example.txt and sets it in read mode. Basically, the file becomes a text object assigned to the variable variableOne.

To read from a file you use the readline() function. It always reads the next line from a text file. So, the variable firstLine will get the first line from the text file as a value. The secondLine will get the second line from the text file as a value.

Next two lines of code just print on the screen the values of the two variables.

Finally, we use the close() function to close the file and free up memory for our program.

Leave a Reply