14

While using os.path.getsize() and os.path.isfile, my script returns the .DS_Store file too which I do not need. How do I ignore those?

import os

root = "/Users/Siddhartha/Desktop/py scripts"
for item in os.listdir(root):
    if os.path.isfile(os.path.join(root, item)):
        print item
user2063763
  • 167
  • 1
  • 1
  • 4
  • 2
    `item.startswith(".")`? – Gareth Latty Mar 05 '13 at 23:02
  • Are you trying to ignore just `.DS_Store`, anything that's considered "hidden" by Finder, anything that's considered "hidden" by Finder or its equivalent on every platform, …? – abarnert Mar 05 '13 at 23:09
  • Or maybe it's a dup of http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection/6365265#6365265 instead, depending on the answer to that question. – abarnert Mar 05 '13 at 23:11
  • I was just trying to ignore .DS_Store. And I agree, it is a duplicate I didn't find those answers when I tried searching for them though. – user2063763 Mar 05 '13 at 23:13
  • If you're just trying to ignore `.DS_Store` why not just `if item != '.DS_Store':`? That avoids having to define exactly what you want "hidden files" to mean (and how you want it to work on other platforms, etc.) and then implement it, which is a much harder problem than just "ignore .DS_Store files". – abarnert Mar 05 '13 at 23:16
  • Meanwhile, the accepted answer on the latter dup refers to an open source project that apparently no longer exists, so… I'm not sure what to do… – abarnert Mar 05 '13 at 23:22

1 Answers1

25

Assuming you want to ignore all files that start with .:

import os

root = "/Users/Siddhartha/Desktop/py scripts"
for item in os.listdir(root):
    if not item.startswith('.') and os.path.isfile(os.path.join(root, item)):
        print item
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Oh I see. Do hidden files always begin with a period? Thanks! – user2063763 Mar 05 '13 at 23:04
  • 2
    On some operating systems that is the case, but not for Windows. For a more generic solution see this answer: http://stackoverflow.com/a/6365265/505154 – Andrew Clark Mar 05 '13 at 23:06
  • It's also not true for Mac OS X, which is the case the OP cares about. Files can be hidden at the filesystem level with attributes. And then, on top of that, as far as NSOpenPanel (or Finder.app) is concerned, they can be hidden at the Finder Info level, or by implicit rules like "don't show "~/Library" (in 10.7+), etc. – abarnert Mar 05 '13 at 23:15