Python for loop for removing files not iterating through entire list

Viewed 24

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.

1 Answers

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('.')]
Related