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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay