0

How can I change this python code to ignore Mac OS' .DS_Store files?

class MySentences(object):
    def __init__(self, dirname):
        self.dirname = dirname

    def __iter__(self):
        for fname in os.listdir(self.dirname):
            for line in open(os.path.join(self.dirname, fname)):
                yield line.split()

Edit: This question looks a lot like this question (How to ignore hidden files using os.listdir()?) but I don't know how to implement that solution into the above class. I tried this:

class MySentences(object):
    def __init__(self, dirname):
        self.dirname = dirname

    def __iter__(self):
        for fname in os.listdir(self.dirname) if not fname.startswith('.'):
            for line in open(os.path.join(self.dirname, fname)):
                yield line.split()

But it didn't work.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
user8998457
  • 61
  • 1
  • 5

1 Answers1

0

You can use an if-statement here by checking that the file name is not equal (!=) to "DS_Store":

class MySentences(object):
    def __init__(self, dirname):
        self.dirname = dirname

    def __iter__(self):
        for fname in os.listdir(self.dirname):
            if fname != '.DS_Store':
                for line in open(os.path.join(self.dirname, fname)):
                    yield line.split()

If the filename does equal this string, then that loop is simply passed-over without the nested for statement being touched.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235