Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in a text file in a set line range

Tags:

python

file

Is it possible to read in from a text file a set line range for example from line 20 to 52?

I am opening the file and reading the file like this:

text_file = open(file_to_save, "r")
line = text_file.readline()

but only want to save the data in a set range or if it possible to read in from a after a line containing --- data --- to another line containing -- end of data --

I have looked through the documentation and online examples and can only find examples that specify a new line or something

like image 432
user2061913 Avatar asked Jul 12 '14 18:07

user2061913


People also ask

How do you read a text file line by line and display each word separated by a?

Open a file in read mode which contains a string. Use for loop to read each line from the text file. Again use for loop to read each word from the line splitted by ' '. Display each word from each line in the text file.

Which method can be used to read individual lines of a file?

We can use RandomAccessFile to open a file in read mode and then use its readLine method to read file line by line.


1 Answers

You can use itertools.islice() on the file object and use iteration to read only specific lines:

import itertools

with open(file_to_save, "r") as text_file:
    for line in itertools.islice(text_file, 19, 52):
         # do something with line

would read lines 20 through to 52; Python uses 0-based indexing, so line 1 is numbered 0.

Using the file object as an iterator gives you a lot of flexibility; you can read extra lines by calling next() on the file object, for example, advancing the line 'pointer' as you do so.

When using the file as an iterable, don't use readline(); the two techniques are not easily mixed.

like image 106
Martijn Pieters Avatar answered Sep 20 '22 08:09

Martijn Pieters