A file doesn't have "lines" or "rows". What you consider a "line" is "what is found between two newline characters". As such you cannot read the nth line without reading the lines before it, as you couldn't count the newline characters.
Answer 1: if you consider your example, but with L=[9], unrolling your loops would give:
i=9
row = [0, {'Col 2': 'row12', 'Col 3': 'row13', 'Col 1': 'row11'}]
As you can see, row is a tuple with two members, calling row[i]
means row[9]
, hence the IndexError.
Answer 2: This is very slow because you are reading the file up to the line number every time. In your example, you read the first 2 lines, then the first 5, then the first 15, then the first 98, etc. So you've read the first 5 lines 3 times. You could create a generator that only returns the lines you want [beware, line numbers would be 0-indexed]:
def read_my_lines[csv_reader, lines_list]:
for line_number, row in enumerate[csv_reader]:
if line_number in lines_list:
yield line_number, row
So when you want to process the lines, you would do:
L = [2, 5, 15, 98, ...]
with open['~/file.csv'] as f:
r = csv.DictReader[f]
for line_number, line in read_my_lines[r, L]:
do_something_with_line[line]
* Edit *
This could further be improved to stop reading the file when you've read all the lines you wanted:
def read_my_lines[csv_reader, lines_list]:
# make sure every line number shows up only once:
lines_set = set[lines_list]
for line_number, row in enumerate[csv_reader]:
if line_number in lines_set:
yield line_number, row
lines_set.remove[line_number]
# Stop when the set is empty
if not lines_set:
raise StopIteration
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways to read specific lines from a text file in python, this article is aimed at discussing them.
File in use: test.txt
Method 1: fileobject.readlines[]
A file object can be created in Python and then readlines[] method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously. It can be easily used to print lines from any random starting index to some ending index. It initially reads the entire content of the file and keep a copy of it in memory. The lines at the specified indices are then accessed.
Example:
Python3
file
=
open
[
'test.txt'
]
content
=
file
.readlines[]
print
[
"tenth line"
]
print
[content[
9
]]
print
[
"first three lines"
]
print
[content[
0
:
3
]]
Output
tenth line
This is line 10.
first three lines
This is line 1.This is line 2.This is line 3.
Method 2: linecache package
The linecache package can be imported in Python and then be used to extract and access specific lines in Python. The package can be used to read multiple lines simultaneously. It makes use of cache storage to perform optimization internally. This package opens the file on its own and gets to the particular line. This package has getline[] method which is used for the same.
Syntax:
getLine[txt-file, line_number]
Example:
Python3
import
linecache
particular_line
=
linecache.getline[
'test.txt'
,
4
]
print
[particular_line]
Output :
This is line 5.
Method 3: enumerate[]
The enumerate[] method is used to convert a string or a list object to a sequence of data indexed by numbers. It is then used in the listing of the data in combination with for loop. Lines at particular indexes can be accessed by specifying the index numbers required in an array.
Example:
Python3
file
=
open
[
"test.txt"
]
specified_lines
=
[
0
,
7
,
11
]
for
pos, l_num
in
enumerate
[
file
]:
if
pos
in
specified_lines:
print
[l_num]
Output
This is line 1. This is line 8. This is line 12.