Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read specific line of file in Python without filling memory

I'm trying to read through a very large text file (> 1.5gb) line by line but would like to avoid loading the whole file into memory, is there a way to just read a specific line at once without loading everything first?

like image 643
user3136883 Avatar asked Sep 16 '25 18:09

user3136883


1 Answers

To read every line one by one you can do

with open('file.txt') as file:
  for line in file:
    print(line)

Actually when you open a file, you will just get a file handle of the file. The file is never fully loaded in memory unless you specifically want to do that.

like image 117
uvdn7 Avatar answered Sep 19 '25 06:09

uvdn7