Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Liệt kê file/thư mục không ẩn trên Windows trong Python

Lọc bỏ file ẩn khi os.listdir().

Hàm is_hidden (giống bài trước)

import os

def is_hidden(path):
    if os.name == 'nt':
        import win32api, win32con
        attrs = win32api.GetFileAttributes(path)
        return bool(attrs & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM))
    return os.path.basename(path).startswith('.')

# Liệt kê non-hidden
file_list = [f for f in os.listdir('.') if not is_hidden(f)]
print(file_list)

pathlib (Python 3.5+)

from pathlib import Path

# Unix-like: bỏ qua tên bắt đầu .
files = [f for f in Path('.').iterdir() if not f.name.startswith('.')]

# Windows: cần check attribute (pathlib chưa có built-in)
# Dùng os.path hoặc win32api như trên