pythonpython-3.xpython-osexfat

macOS - os.listdir returns double items which starts with "."?


Despite that the folder has two files (a.apk, and b.apk), os.listdir function returns four files such as ._b.apk, ._a.apk, a.apk, and b.apk. Where do the first two files come from? How can I prevent Python to list them?

Software Stack:

- OS: macOS Catalina
- Python: 3.7.3

p.s. The files are stored in an external flash drive, which is formatted as ExFAT.


Solution

  • Where do the first two files come from?

    For this part, see this question: https://apple.stackexchange.com/questions/14980/why-are-dot-underscore-files-created-and-how-can-i-avoid-them

    How can I prevent Python to list them?

    Neither os.listdir() nor os.walk() nor os.path.walk() (only in Python 2) have a parameter immediately suppressing this kind of files, as for the underlying OS, these are normal files. It's the UI which makes this distinction.

    So you'll have to do it on your own:

    files = [i for i in os.listdir(".") if not i.startswith("._")]
    

    would be one option.

    If you want to suppress all hidden files (i. e., all files which start with a .), do

    files = [i for i in os.listdir(".") if not i.startswith(".")]
    

    instead.