-2

I am trying to pull in all the files in a specific directory using the os library for python.

The loop i created goes through 3 times but still leaves some items.

MacOS btw

import os

path = r"my_path"

files = os.list(path)

for file in files:
    if file.startswith('.') : files.remove(file)

I tried running the for loop again after the first loop and it removes another problem files, but still leaves another.

Any direction would be much appreciated. Thanks, have a good one.

ChanMan
  • 11
  • 3

1 Answers1

1

Don't remove items from a list that you're iterating over; the indices all shift and the iterator will end up skipping items. Instead, build a new list:

files = [file for file in files if not file.startswith('.')]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Ok will try this. Question though. Would a sort() in the for loop prevent this? Thanks so much for the fast reply. – ChanMan Sep 24 '22 at 04:40
  • No, sorting the thing you're iterating is just as bad as removing items from the thing you're iterating. Don't change the order or number of elements in the thing you're iterating over while you're still in the middle of the iteration. – Samwise Sep 24 '22 at 14:15
  • ahh gotcha. I didnt understand late last night but i see exactly what you mean now. thanks a lot for helping a noob. – ChanMan Sep 24 '22 at 14:31