Why can't i divide index loop integer with lenght of with open text file in Python?

Viewed 31

I got a piece of code like this

    with open(r'D:\Workstuff\my-work-python-script\Auto_Tracker (dev)\retrieve_tracking.txt', 'r+') as text: #fetch all value
        for index, value in enumerate(text):
           if index % 49 == 0 and index != 0:
               driver.find_element(By.ID,'trackItNowForm:searchSkuBtn').click()
           elif index % len(text.readlines()) == 0 and index != 0:
               driver.find_element(By.ID,'trackItNowForm:searchSkuBtn').click()

I'm trying to fetch all the data in my text file and if i reach the last line in the file, Simply stop the loop and move on to next function. I also want it to limit only 50 lines.

The file i'm about to fetch have only 44 lines. So i though by condition if similar to above would solve the issue. But instead i got an error

'ZeroDivisionError: integer division or modulo by zero'

I tried printing the value i need to fetch and...

    for index, value in enumerate(text): #iterate through all of them first
        print(f'Total Line :{len(text.readlines())}')
        print(f'Index = {index}')

The Result is 'Total Line : 44\nIndex = 0' Basically, The lenght is clearly not zero so now the error got me really confused there. Anyone know what happen here?

2 Answers

You might have a problem with the enumerate advancing the file cursor every time you iterate.

readlines will read from the current file cursor position, so when that is already at the end of the file, text.readlines() returns an empty list.

Try storing the length at the beginning and then use text.seek(0) before starting the loop.

    with open(r'D:\Workstuff\my-work-python-script\Auto_Tracker (dev)\retrieve_tracking.txt', 'r+') as text: #fetch all value
        file_len = len(text.readlines())
        text.seek(0)
        for index, value in enumerate(text):
           if index % 49 == 0 and index != 0:
               driver.find_element(By.ID,'trackItNowForm:searchSkuBtn').click()
           elif index % file_len == 0 and index != 0:
               driver.find_element(By.ID,'trackItNowForm:searchSkuBtn').click()

It's because the file has one line only. So, you go into the for loop, and read the line. Then in the elif, text.readlines() returns nothing, because the first line was already read. So len(..) gives 0 which gives the divide by zero error. You can check the file length with os.path.getsize(path)

Related