0

There are similar questions to this but not quite what im looking for.

Having created a list with all files from a specific path im looking to filter out anything that does not contain a specific sequence in a string.

def filter():
    someFiles = os.listdir(somePath)
    listSize = len(someFiles)

    for i in range(0, listSize):
        if (".py" not in someFiles):
            someFiles.remove(i)
            print("{0}".format(someFiles))

Im aware i shouldn't be modifying the size of a list through a loop but i left it just to roughly give an idea of what i'm trying to accomplish

I did not make it clear, the issue that im facing is that i'm not sure what approach i should be taking when trying to remove every element that does not contain ".py". What I wrote above is more of a rough draft.

4
  • 1
    what problem did you face... Commented Aug 16, 2016 at 12:59
  • 2
    You could create a new list based on the old one: files = [f for f in someFiles if ".py" not in f] Commented Aug 16, 2016 at 13:00
  • 1
    @pschill Using this approach requires if ".py" in f (note that OP removes the files that don't have '.py' in them). Commented Aug 16, 2016 at 13:05
  • @DeepSpace Yes you are right. I misread that. Commented Aug 16, 2016 at 13:40

2 Answers 2

3
for i in range(0, listSize):
    if (".py" not in someFiles):
        someFiles.remove(i)

Note that you are trying to remove i from the list. i will be an index of an element in the list (0, 1, etc) and not an actual element. This will raise an error.


Simply use list comprehension to get only the files you do need:

required_files = [f for f in someFiles if '.py' in f]

You could also use filter but it will require a lambda (and also note it will return a filter object and not a list):

required_files = list(filter(lambda x: '.py' in x, someFiles))
Sign up to request clarification or add additional context in comments.

1 Comment

Right, my logic was off, this is what i was trying to do. Thank you
1

First of all, you don't need to use for loop to iterate over a list in Python. Simpler version of what you've done would be

list2 = []
for filename in list1:
    if (".py" in filename):
        list2.append(filename)

but filtering a list (or more generally, an iterator) is so common, that there is Python builtin function called, unsurprisingly, filter:

list2 = list(filter(lambda i: ".py" in i, list1))

(this would work at least in Python3)

1 Comment

Yeah i dont know why i was trying to remove, this works perfect. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.