0

How to ignore hidden folders from os.scandir() in Python 3.10.x?

import os

for dir in os.scandir('C:/'):
    print(dir.path)

I don't want these paths.

enter image description here

I want these paths.

enter image description here

Karan
  • 65
  • 6

2 Answers2

0

This post is for hidden files but it should work for folders as well: Cross platform hidden file detection

SimonUnderwood
  • 469
  • 3
  • 12
0

Here is the folder which contains 1 hidden folder and a file. They get ignored in the final output and only non-hidden directories are getting listed:

enter image description here

import os

    if os.name == 'nt':
        import win32api, win32con
    def file_is_hidden(p):
        if os.name== 'nt':
            attribute = win32api.GetFileAttributes(p)
            return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
        else:
            return p.startswith('.') #linux-osx
    file_list = [f for f in os.listdir(".") if not file_is_hidden(f) and os.path.isdir(f)]
    print(file_list)

Output:

    ['1', '2']
Ali
  • 350
  • 3
  • 10