'python enumerate looping through a file [duplicate]
How does this enumerate works? I want a specific starting index but yet the loop goes too far(index out of range)
def endingIndexOfTable(file, index):
r = re.compile('^V.*(.).*(.).*(.).*(-).*(-).*(.).*(.).*(:).*$')
for i, line in enumerate(file, start= index):
if list(filter(r.match, line)) or "Sales Tax" in line:
return i
I want my program to start searching from line index and to return the line where I find the string I am looking for.
Solution 1:[1]
I don't think you can start at a specific line of a file. I think you have to skip all the preceding lines first:
def endingIndexOfTable(file, index):
r = re.compile('^V.*(.).*(.).*(.).*(-).*(-).*(.).*(.).*(:).*$')
for i, line in enumerate(file):
if i >= index:
if list(filter(r.match, line)) or "Sales Tax" in line:
return i
Although, did you mean return line?
Then, the version with islice should be like this:
from itertools import islice
def endingIndexOfTable(file, index):
r = re.compile('^V.*(.).*(.).*(.).*(-).*(-).*(.).*(.).*(:).*$')
for i, line in islice(enumerate(file), index, None):
if list(filter(r.match, line)) or "Sales Tax" in line:
return i
(again assuming that both the regex and the return are correct)
Solution 2:[2]
EDIT
I screwed up in the same way as OP. This does not answer the question.
I don't want to deal with your regex, but here's one way to achieve the logic you need for searching from a specific line. It would load the entire file in memory though, and not actually read just the specific line.
poem.txt is just the file I used to test. Contents:
Author of the poem is: Me
poem is called: Test
AAFgz
S2zergtrxbhcn
Dzrgxt
Frhgc
Gzxcnhvjzx
xghrfcan a
jvzxhdyrfcv
kh
def read_by_line(file, index):
for i, line in enumerate(file.readlines(), start=index):
print(line)
if "a" in line: # if condition could have been your regex stuff
return i
with open('poem.txt', 'r') as file_object:
print(read_by_line(file_object, 5))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
