DEV Community

Mahendra Patel
Mahendra Patel

Posted on

File reading in python

Generally, file.read() method is used to read entire content of the file. But what if file is too big?
In such cases file.readline() and file.readlines() came to rescue.

with open('abc.txt', 'r', encoding='utf-8') as file:
    pass

Enter fullscreen mode Exit fullscreen mode

In the above code open() method return a stream/ file object, which didn't load anything in the memory. To read content of the file, we have 3 choices

1. read()

Read entire file and load all the content in the memory, optionally it can also take number of characters to load as first argument, but in most of the case we don't know the number of characters before hand.

2. readline()

Since file object return a stream, IOStream are actually iterable, so we can use next() method or for loop to get all the lines one by one, and do want-ever we want to do

3. readlines()

If no argument passed, it will also return entire file, but as a list, where one line represented by one element of the list, but you can also specify the number of lines you want to read at a time

To summerize

Python file object is a stream, and you have multiple option to read the file content, without loading entire file into the memory, so you can easily work with files without worrying about file size.

Top comments (0)