Home > Mobile >  How do I solve this IndexError inside a for Loop?
How do I solve this IndexError inside a for Loop?

Time:09-21

I have been playing around with Python for over a year now and written several automation codes which I use on a daily basis. I have been writing this auto typer for Python, here is the code:

import pyautogui as pt
from time import sleep

empty_file = "C:\\Users\\Lucas\\Desktop\\PycharmProjects\\Automate\\main\\screenshots\\empty_file.png"
text_write = "C:\\Users\\Lucas\\Desktop\\PycharmProjects\\Automate\\main\\text_write.txt"

with open(text_write, 'r') as f:
    text = f.read()
    sentence = text.split("\n")

position0 = pt.locateOnScreen(empty_file, confidence=.8)
x = position0[0]
y = position0[1]
pt.moveTo(x, y, duration=.05)
pt.leftClick()

def post_text():
    pt.moveTo(x-370, y 95, duration=.1)
    for lines in range(len(text)):
        pt.typewrite(str(sentence[lines],)   "\n", interval=.01)
        with pt.hold('shift'):
            pt.press('tab', presses=5)
        sleep(2)


post_text()

The code completely works but at the end instead of the code breaking it gives me this error:

C:\Users\Lucas\PycharmProjects\wechat_bot\venv\Scripts\python.exe C:/Users/Lucas/Desktop/PycharmProjects/Automate/main/auto_typer.py
Traceback (most recent call last):
  File "C:\Users\Lucas\Desktop\PycharmProjects\Automate\main\auto_typer.py", line 26, in <module>
    post_text()
  File "C:\Users\Lucas\Desktop\PycharmProjects\Automate\main\auto_typer.py", line 20, in post_text
    pt.typewrite(str(sentence[lines],)   "\n", interval=.01)
IndexError: list index out of range

Process finished with exit code 1

I suspect the issue has to do specifically with the line:

str(sentence[lines],

I haven't found a solution yet. Am I supposed to be using len() or would and if else statement be better?

CodePudding user response:

The problem is that you are doing

    for lines in range(len(text)):

but then you later do

sentence[lines]

This will only work text is shorter than or the same length as sentence. But there is no such guarantee in your code.

Instead, you should do

    for lines in range(len(sentence)):

Or better yet loop over the lines without indexes:

for line in sentence:

And then you can just do line instead of sentence[lines].

  • Related