Reputation: 15
I am using the following code to read a text file and create an array list out of the text found in the file. But currently I am reading the whole file. How can I read for example from line no. 16 onwards in this case?
array = []
with open(path, 'r') as f:
for line in f.readlines():
for action in all_actions:
if action in line:
array.append(action)
Upvotes: 0
Views: 138
Reputation: 4472
You can use
array = []
exit_line = 16
start_line = 10
with open(path, 'r') as f:
for index, line in enumerate(f.readlines()[start_line:]):
for action in all_actions:
if action in line:
array.append(action)
if index == exit_line - 1:
break
and then to make an if condition to exit/ break at line 16 that is the index +1 .
Upvotes: 1
Reputation: 2323
Try (explanation in code comments):
array = []
with open('path', 'r') as f:
# x here is a loop (lines) counter provided by the enumerate function
for x, line in enumerate(f.readlines()):
for action in all_actions:
if action in line:
array.append(action)
# if the counter reaches 16 BREAK out of the loop
if x == 16:
print ("Line 16 exiting loop")
break
Upvotes: 1