|
23 | 23 | import io |
24 | 24 | import shutil |
25 | 25 |
|
| 26 | +scandir = None |
| 27 | +try: |
| 28 | + scandir = os.scandir |
| 29 | +except AttributeError: |
| 30 | + try: |
| 31 | + from scandir import scandir |
| 32 | + except ImportError: |
| 33 | + pass |
| 34 | + |
26 | 35 | from fs.base import * |
27 | 36 | from fs.path import * |
28 | 37 | from fs.errors import * |
@@ -248,9 +257,24 @@ def isfile(self, path): |
248 | 257 | def listdir(self, path="./", wildcard=None, full=False, absolute=False, dirs_only=False, files_only=False): |
249 | 258 | _decode_path = self._decode_path |
250 | 259 | sys_path = self.getsyspath(path) |
251 | | - listing = os.listdir(sys_path) |
252 | | - paths = [_decode_path(p) for p in listing] |
253 | | - return self._listdir_helper(path, paths, wildcard, full, absolute, dirs_only, files_only) |
| 260 | + |
| 261 | + if scandir is None: |
| 262 | + listing = os.listdir(sys_path) |
| 263 | + paths = [_decode_path(p) for p in listing] |
| 264 | + return self._listdir_helper(path, paths, wildcard, full, absolute, dirs_only, files_only) |
| 265 | + else: |
| 266 | + if dirs_only and files_only: |
| 267 | + raise ValueError("dirs_only and files_only can not both be True") |
| 268 | + # Use optimized scandir if present |
| 269 | + scan = scandir(sys_path) |
| 270 | + if dirs_only: |
| 271 | + paths = [_decode_path(dir_entry.name) for dir_entry in scan if dir_entry.is_dir()] |
| 272 | + elif files_only: |
| 273 | + paths = [_decode_path(dir_entry.name) for dir_entry in scan if dir_entry.is_file()] |
| 274 | + else: |
| 275 | + paths = [_decode_path(dir_entry.name) for dir_entry in scan] |
| 276 | + |
| 277 | + return self._listdir_helper(path, paths, wildcard, full, absolute, False, False) |
254 | 278 |
|
255 | 279 | @convert_os_errors |
256 | 280 | def makedir(self, path, recursive=False, allow_recreate=False): |
|
0 commit comments