Kumar Patel Kumar Patel - 25 days ago 5
Python Question

While loop index error

I want Python to constantly scan a folder and as soon as a new file is created in the folder to start the rest of the code.

However I am stuck here:

import os

os.chdir("path")
a = os.listdir("path")
initial = len(a)


while True:
b = os.listdir("path")
final = len(b)
if final > initial:
c = list(set(b) - set(a))
a.append(c[0])


c[0] is appended to list a however the code then crashes with this error


a.append(c[0]) IndexError: list index out of range


Answer

This happens because c is empty. So the easiest way to make this line work is:

import os

os.chdir("path")
a = os.listdir("path")
initial = len(a)

while True:
    b = os.listdir("path")
    final = len(b)
    if final > initial:
        c = list(set(b) - set(a))
        if c:
            a.append(c[0])

And while True without break statement is not that good idea...