1

Is there a way to so some type of set of file extension types instead of all of the redundant OR conditions?

for file in os.listdir(source_directory):
    if file.endswith(".xlsx") or file.endswith(".xls") or file.endswith(".xlsm") or file.endswith(".xlsb"):

So something like

if file.endswith(".xlsx","xls","xlsm","xlsb"):
Rodger
  • 13
  • 1
  • 4

1 Answers1

4

Quoting official docs (emphasis mine):

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

Changed in version 2.5: Accept tuples as suffix.

So correct usage will be:

for file in os.listdir(source_directory):
    if file.endswith((".xlsx","xls","xlsm","xlsb")):
        pass  # do something
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93