Windows 10环境下Python 3.8快速判断是否为目录(isDir)的高效方法
If you're dealing with large volumes of files and directories and hitting brutal performance bottlenecks with os.path.isdir(), the best Windows 10-specific solution is to leverage os.scandir() from Python's standard library. Here's why it works and how to implement it:
Why os.path.isdir() is so slow
Every call to os.path.isdir() triggers a separate system API request to query the filesystem for that path's attributes. When you're checking tens of thousands of entries, these repeated calls pile up into massive overhead—exactly the 17-second vs 0.48-second gap you saw.
The Fast Fix: os.scandir()
Added in Python 3.5 (which your 3.8 version fully supports), os.scandir() is built for this exact scenario. It fetches metadata for all entries in a directory in a single batch system call, and returns DirEntry objects that cache this metadata. The is_dir() method on these objects doesn’t require an extra system call—it just reads the pre-fetched data.
Example 1: Iterate directly with scandir
Instead of first grabbing a list of filenames and validating each one separately, iterate with scandir to get directory status in-line:
import os target_dir = "your/target/directory/path" # Fast, accurate iteration with os.scandir(target_dir) as entries: for entry in entries: if entry.is_dir(): # Handle directory logic here print(f"Found directory: {entry.name}") else: # Handle file logic here print(f"Found file: {entry.name}")
Example 2: Pre-cache directory status for existing filename lists
If you already have a list of filenames and need to check their status repeatedly, build a lookup dictionary once with scandir:
import os target_dir = "your/target/directory/path" # Build a one-time cache: filename -> is_directory dir_status_cache = {} with os.scandir(target_dir) as entries: for entry in entries: dir_status_cache[entry.name] = entry.is_dir() # Now check filenames in O(1) time your_filename_list = ["document.txt", "config_folder", "README"] for filename in your_filename_list: is_dir = dir_status_cache.get(filename, False) print(f"{filename}: {'Directory' if is_dir else 'File'}")
Performance Impact
For your use case, this should bring speeds close to your (but incorrect) '.' not in filename check. In real-world tests with large directories, scandir-based checks can be 10-100x faster than repeated os.path.isdir() calls.
Skip the Hacky Workarounds
Avoid relying on filename patterns (like missing dots)—as you already know, directories can have dots (e.g., my.config.dir) and files can lack them (e.g., LICENSE). The scandir approach is both blazingly fast and 100% accurate.
内容的提问来源于stack exchange,提问作者Redwings

