Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to read 10000 lines from a file in python?

Tags:

python

I am relatively new in python, was working on C a lot. Since I was seeing so many new functions in python that I do not know, I was wondering if there is a function that can request 10000 lines from a file in python.

Something like this is what I expect if that kind of function exist:

lines = get_10000_lines(file_pointer)

Did python have a build-in function or is there any module that I can download for this? If not, how do I do this to be easiest way. I need to analyze a huge file so I want to read 10000 lines and analyze per time to save memory.

Thanks for helping!

like image 265
windsound Avatar asked Jun 18 '12 21:06

windsound


People also ask

How do I read 10 lines from a file in Python?

Use readlines() to Read the range of line from the File The readlines() method reads all lines from a file and stores it in a list. You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python.

How do I read many lines in Python?

To read multiple lines, call readline() multiple times. The built-in readline() method return one line at a time. To read multiple lines, call readline() multiple times.

How do I read a large data file in Python?

Reading Large Text Files in Python We can use the file object as an iterator. The iterator will return each line one by one, which can be processed. This will not read the whole file into memory and it's suitable to read large files in Python.


1 Answers

f.readlines() returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to load the entire file in memory. Only complete lines will be returned.

From the docs.

This is not exactly what you were asking for, as this is limiting the bytes read instead of the lines read, but I think this is what you want to do instead.

like image 196
ChipJust Avatar answered Sep 18 '22 08:09

ChipJust