The readlines() method

Consider the situation where you want to make a list of lines of a file; in that case, the readlines() method allows you to do that.

See the code in readlines1.py:

file_input = open("sample1.txt",'r')
print file_input.readlines()
file_input.close()

Let's check the output of the code:

In the preceding screenshot, you can easily see the list of lines.

For reading purposes, you can loop over the file object. Let's analyze the code in readfileforloop.py:

file_input = open("sample1.txt",'r')
for line in file_input:
print line

This is the output:

You can see all the lines. This is memory efficient, fast, and leads to simple code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.79.176