Reputation: 1190
I have the following code:
with open('data.csv') as csvfile:
data = csv.reader(csvfile, delimiter=' ')
print(data)
row_count = row_count = sum(1 for lines in data)
print(row_count)
csvfile.seek(0)
counter = 0
while counter <= row_count:
for i in range(20):
for row in data:
print(row_count)
for ticker in row:
print(ticker)
counter = counter + 1
print('sleep')
t.sleep(10)
The while loop will work till there is lines in the data variable. What i want to do is read the first 20 lines in data and then sleep for 10 seconds and start reading the second batch of 20 lines and then sleep for 10 seconds.
When i execute this what is actually happening is it runs through the entire list and then sleeps and prints row_count
and sleeps again instead of sleep after first 20 lines. The while loop should also end after reaching row_count
Upvotes: 0
Views: 53
Reputation: 77857
Look at your indentation: you put your sleep
inside the 20-iteration loop, telling it to sleep on every iteration.
counter = 0
while counter <= row_count:
for i in range(20):
for row in data:
print(row_count)
for ticker in row:
print(ticker)
counter = counter + 1
print('sleep')
t.sleep(10)
If you don't want to do that, then pull the sleep
out to where you do want it.
Note that you're going to hit the same problem as in your previous question: you read all the data in the inner loop; there won't be anything left after you come back for the second iteration.
for i in range(20):
for row in data:
You're reading the entire file 20 times. OOPS.
Think in terms of flow control first: you want to read the file, one line at a time. Every 20th line, you want to sleep, then resume reading where you left off. The main purpose is read the file once, but keep track of the line count.
for counter, line in enumerate(data):
print(row_count)
for ticker in row:
print(ticker)
if counter % 20 == 19: # Completed lines 0-19 of this batch; nap time.
print('sleep')
t.sleep(10)
Upvotes: 1