Read a file

Reading the contents of a file in Python is straightforward and there are a couple of nice methods that cater for different use cases.

OPEN THE FILE

Suppose we want to read a file called my_text.txt. First, we open the file:

f = open('my_text.txt', 'r')

We now have the file as an object, f

READ THE ENTIRE FILE INTO A STRING

For most use cases, it's enough to simply read the entire contents of the file into a string. We can do this by using Python's read() method. 

content = f.read()
print (content)

READ THE ALL OF THE LINES IN THE FILE INTO A LIST

Sometimes, you're going to want to deal with the file you're working with at line level. Fortunately, Python's readlines() method is available. The readlines() stores each line in the file to be read as an item in a list.

content = f.readlines()

READ A SPECIFIC LINE IN THE FILE

There maybe times were you want to read a specific line in the file, which is what the readline() method can be used for. 

To access the first line in the file:

content = f.readline()

To access the second line in the file (remember Python is zero-indexed):

content = f.readline(1)