8

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

2

3 Answers 3

28

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you wanted to read a sample of lines from a file, would you need to read them sequentially? OR - if you want to read lines 25 and 12, should you read line 12 first?
@wwii: you can do random access (using file.seek()), but then you have to search for the newlines manually, and you can't know the count of lines. Unless your file format uses fixed-length lines, it is just way, way easier to read sequentially if you need to read specific lines.
8

You can do two things. You can use enumerate(), and use an if statement:

text_file = open(file_to_save, "r") lines = [] for index, text in enumerate(text_file): if 19 <= index <= 51: lines.append(text) 

Or instead, you can use readlines() and then slice:

text_file = open(file_to_save, "r") lines = text_file.readlines() lines = lines[19:52] 

1 Comment

'readline()' should be 'readlines()' in the second to last line
-1

HM,you can try something with while loop....but you should know up to which string you want text to be loaded,which is not best way:

text_file=open(name,'r') line=text.readline() while line!=(" ") #type the line where you want it to stop print (line 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.