FabricioG
FabricioG

Reputation: 3310

python if file name is "blah" AND "blah"

I'm trying to figure out if my file name contains two values.
I've done this to find a certain file name extension:

import os
for root, dirs, files in os.walk("myDir"):
  for file in files:
    if file.endswith(".jpg"):
      print(os.path.join(root, file))

Now I want to do something like this:

import os
for root, dirs, files in os.walk("myDir"):
  for file in files:
    if file.contains("string1" & "string2"):
      print(os.path.join(root, file))

Obivously the above won't work because there's no "contains" in python string method. I saw a find but I couldn't figure out how to work it with two values.

The idea is that if a file name has "state" & "california" then it would print. In this example "iliveinstateofcalifornia.jpg" would print.

Upvotes: 0

Views: 357

Answers (2)

Jacob
Jacob

Reputation: 926

There may not be a contains() method, but there is the keyword 'in'. For example,

if 'state' in file and 'California' in file:
  print('Do things with stuff')

That said, there are almost certainly more efficient ways of checking string containment. If the filenames have the same format and you will be repeatedly checking against many filenames, it will probably be more performant to employ a compiled regular expression. For more information, refer to the documentation of the Python module "re", available here.

Upvotes: 1

schillingt
schillingt

Reputation: 13731

You can make use of the all function. That way you can expand the list without having to change the if conditions.

values = ['string1', 'string2']
if all(file.contains(value) for value in values):
    # Do something

Upvotes: 2

Related Questions