scandir.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. """scandir, a better directory iterator and faster os.walk(), now in the Python 3.5 stdlib
  2. scandir() is a generator version of os.listdir() that returns an
  3. iterator over files in a directory, and also exposes the extra
  4. information most OSes provide while iterating files in a directory
  5. (such as type and stat information).
  6. This module also includes a version of os.walk() that uses scandir()
  7. to speed it up significantly.
  8. See README.md or https://github.com/benhoyt/scandir for rationale and
  9. docs, or read PEP 471 (https://www.python.org/dev/peps/pep-0471/) for
  10. more details on its inclusion into Python 3.5
  11. scandir is released under the new BSD 3-clause license. See
  12. LICENSE.txt for the full license text.
  13. """
  14. from __future__ import division
  15. from errno import ENOENT
  16. from os import listdir, lstat, stat, strerror
  17. from os.path import join, islink
  18. from stat import S_IFDIR, S_IFLNK, S_IFREG
  19. import collections
  20. import os
  21. import sys
  22. try:
  23. import _scandir
  24. except ImportError:
  25. _scandir = None
  26. try:
  27. import ctypes
  28. except ImportError:
  29. ctypes = None
  30. if _scandir is None and ctypes is None:
  31. import warnings
  32. warnings.warn("scandir can't find the compiled _scandir C module "
  33. "or ctypes, using slow generic fallback")
  34. __version__ = '1.5'
  35. __all__ = ['scandir', 'walk']
  36. # Windows FILE_ATTRIBUTE constants for interpreting the
  37. # FIND_DATA.dwFileAttributes member
  38. FILE_ATTRIBUTE_ARCHIVE = 32
  39. FILE_ATTRIBUTE_COMPRESSED = 2048
  40. FILE_ATTRIBUTE_DEVICE = 64
  41. FILE_ATTRIBUTE_DIRECTORY = 16
  42. FILE_ATTRIBUTE_ENCRYPTED = 16384
  43. FILE_ATTRIBUTE_HIDDEN = 2
  44. FILE_ATTRIBUTE_INTEGRITY_STREAM = 32768
  45. FILE_ATTRIBUTE_NORMAL = 128
  46. FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192
  47. FILE_ATTRIBUTE_NO_SCRUB_DATA = 131072
  48. FILE_ATTRIBUTE_OFFLINE = 4096
  49. FILE_ATTRIBUTE_READONLY = 1
  50. FILE_ATTRIBUTE_REPARSE_POINT = 1024
  51. FILE_ATTRIBUTE_SPARSE_FILE = 512
  52. FILE_ATTRIBUTE_SYSTEM = 4
  53. FILE_ATTRIBUTE_TEMPORARY = 256
  54. FILE_ATTRIBUTE_VIRTUAL = 65536
  55. IS_PY3 = sys.version_info >= (3, 0)
  56. if IS_PY3:
  57. unicode = str # Because Python <= 3.2 doesn't have u'unicode' syntax
  58. class GenericDirEntry(object):
  59. __slots__ = ('name', '_stat', '_lstat', '_scandir_path', '_path')
  60. def __init__(self, scandir_path, name):
  61. self._scandir_path = scandir_path
  62. self.name = name
  63. self._stat = None
  64. self._lstat = None
  65. self._path = None
  66. @property
  67. def path(self):
  68. if self._path is None:
  69. self._path = join(self._scandir_path, self.name)
  70. return self._path
  71. def stat(self, follow_symlinks=True):
  72. if follow_symlinks:
  73. if self._stat is None:
  74. self._stat = stat(self.path)
  75. return self._stat
  76. else:
  77. if self._lstat is None:
  78. self._lstat = lstat(self.path)
  79. return self._lstat
  80. def is_dir(self, follow_symlinks=True):
  81. try:
  82. st = self.stat(follow_symlinks=follow_symlinks)
  83. except OSError as e:
  84. if e.errno != ENOENT:
  85. raise
  86. return False # Path doesn't exist or is a broken symlink
  87. return st.st_mode & 0o170000 == S_IFDIR
  88. def is_file(self, follow_symlinks=True):
  89. try:
  90. st = self.stat(follow_symlinks=follow_symlinks)
  91. except OSError as e:
  92. if e.errno != ENOENT:
  93. raise
  94. return False # Path doesn't exist or is a broken symlink
  95. return st.st_mode & 0o170000 == S_IFREG
  96. def is_symlink(self):
  97. try:
  98. st = self.stat(follow_symlinks=False)
  99. except OSError as e:
  100. if e.errno != ENOENT:
  101. raise
  102. return False # Path doesn't exist or is a broken symlink
  103. return st.st_mode & 0o170000 == S_IFLNK
  104. def inode(self):
  105. st = self.stat(follow_symlinks=False)
  106. return st.st_ino
  107. def __str__(self):
  108. return '<{0}: {1!r}>'.format(self.__class__.__name__, self.name)
  109. __repr__ = __str__
  110. def _scandir_generic(path=unicode('.')):
  111. """Like os.listdir(), but yield DirEntry objects instead of returning
  112. a list of names.
  113. """
  114. for name in listdir(path):
  115. yield GenericDirEntry(path, name)
  116. if IS_PY3 and sys.platform == 'win32':
  117. def scandir_generic(path=unicode('.')):
  118. if isinstance(path, bytes):
  119. raise TypeError("os.scandir() doesn't support bytes path on Windows, use Unicode instead")
  120. return _scandir_generic(path)
  121. scandir_generic.__doc__ = _scandir_generic.__doc__
  122. else:
  123. scandir_generic = _scandir_generic
  124. scandir_c = None
  125. scandir_python = None
  126. if sys.platform == 'win32':
  127. if ctypes is not None:
  128. from ctypes import wintypes
  129. # Various constants from windows.h
  130. INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
  131. ERROR_FILE_NOT_FOUND = 2
  132. ERROR_NO_MORE_FILES = 18
  133. IO_REPARSE_TAG_SYMLINK = 0xA000000C
  134. # Numer of seconds between 1601-01-01 and 1970-01-01
  135. SECONDS_BETWEEN_EPOCHS = 11644473600
  136. kernel32 = ctypes.windll.kernel32
  137. # ctypes wrappers for (wide string versions of) FindFirstFile,
  138. # FindNextFile, and FindClose
  139. FindFirstFile = kernel32.FindFirstFileW
  140. FindFirstFile.argtypes = [
  141. wintypes.LPCWSTR,
  142. ctypes.POINTER(wintypes.WIN32_FIND_DATAW),
  143. ]
  144. FindFirstFile.restype = wintypes.HANDLE
  145. FindNextFile = kernel32.FindNextFileW
  146. FindNextFile.argtypes = [
  147. wintypes.HANDLE,
  148. ctypes.POINTER(wintypes.WIN32_FIND_DATAW),
  149. ]
  150. FindNextFile.restype = wintypes.BOOL
  151. FindClose = kernel32.FindClose
  152. FindClose.argtypes = [wintypes.HANDLE]
  153. FindClose.restype = wintypes.BOOL
  154. Win32StatResult = collections.namedtuple('Win32StatResult', [
  155. 'st_mode',
  156. 'st_ino',
  157. 'st_dev',
  158. 'st_nlink',
  159. 'st_uid',
  160. 'st_gid',
  161. 'st_size',
  162. 'st_atime',
  163. 'st_mtime',
  164. 'st_ctime',
  165. 'st_atime_ns',
  166. 'st_mtime_ns',
  167. 'st_ctime_ns',
  168. 'st_file_attributes',
  169. ])
  170. def filetime_to_time(filetime):
  171. """Convert Win32 FILETIME to time since Unix epoch in seconds."""
  172. total = filetime.dwHighDateTime << 32 | filetime.dwLowDateTime
  173. return total / 10000000 - SECONDS_BETWEEN_EPOCHS
  174. def find_data_to_stat(data):
  175. """Convert Win32 FIND_DATA struct to stat_result."""
  176. # First convert Win32 dwFileAttributes to st_mode
  177. attributes = data.dwFileAttributes
  178. st_mode = 0
  179. if attributes & FILE_ATTRIBUTE_DIRECTORY:
  180. st_mode |= S_IFDIR | 0o111
  181. else:
  182. st_mode |= S_IFREG
  183. if attributes & FILE_ATTRIBUTE_READONLY:
  184. st_mode |= 0o444
  185. else:
  186. st_mode |= 0o666
  187. if (attributes & FILE_ATTRIBUTE_REPARSE_POINT and
  188. data.dwReserved0 == IO_REPARSE_TAG_SYMLINK):
  189. st_mode ^= st_mode & 0o170000
  190. st_mode |= S_IFLNK
  191. st_size = data.nFileSizeHigh << 32 | data.nFileSizeLow
  192. st_atime = filetime_to_time(data.ftLastAccessTime)
  193. st_mtime = filetime_to_time(data.ftLastWriteTime)
  194. st_ctime = filetime_to_time(data.ftCreationTime)
  195. # Some fields set to zero per CPython's posixmodule.c: st_ino, st_dev,
  196. # st_nlink, st_uid, st_gid
  197. return Win32StatResult(st_mode, 0, 0, 0, 0, 0, st_size,
  198. st_atime, st_mtime, st_ctime,
  199. int(st_atime * 1000000000),
  200. int(st_mtime * 1000000000),
  201. int(st_ctime * 1000000000),
  202. attributes)
  203. class Win32DirEntryPython(object):
  204. __slots__ = ('name', '_stat', '_lstat', '_find_data', '_scandir_path', '_path', '_inode')
  205. def __init__(self, scandir_path, name, find_data):
  206. self._scandir_path = scandir_path
  207. self.name = name
  208. self._stat = None
  209. self._lstat = None
  210. self._find_data = find_data
  211. self._path = None
  212. self._inode = None
  213. @property
  214. def path(self):
  215. if self._path is None:
  216. self._path = join(self._scandir_path, self.name)
  217. return self._path
  218. def stat(self, follow_symlinks=True):
  219. if follow_symlinks:
  220. if self._stat is None:
  221. if self.is_symlink():
  222. # It's a symlink, call link-following stat()
  223. self._stat = stat(self.path)
  224. else:
  225. # Not a symlink, stat is same as lstat value
  226. if self._lstat is None:
  227. self._lstat = find_data_to_stat(self._find_data)
  228. self._stat = self._lstat
  229. return self._stat
  230. else:
  231. if self._lstat is None:
  232. # Lazily convert to stat object, because it's slow
  233. # in Python, and often we only need is_dir() etc
  234. self._lstat = find_data_to_stat(self._find_data)
  235. return self._lstat
  236. def is_dir(self, follow_symlinks=True):
  237. is_symlink = self.is_symlink()
  238. if follow_symlinks and is_symlink:
  239. try:
  240. return self.stat().st_mode & 0o170000 == S_IFDIR
  241. except OSError as e:
  242. if e.errno != ENOENT:
  243. raise
  244. return False
  245. elif is_symlink:
  246. return False
  247. else:
  248. return (self._find_data.dwFileAttributes &
  249. FILE_ATTRIBUTE_DIRECTORY != 0)
  250. def is_file(self, follow_symlinks=True):
  251. is_symlink = self.is_symlink()
  252. if follow_symlinks and is_symlink:
  253. try:
  254. return self.stat().st_mode & 0o170000 == S_IFREG
  255. except OSError as e:
  256. if e.errno != ENOENT:
  257. raise
  258. return False
  259. elif is_symlink:
  260. return False
  261. else:
  262. return (self._find_data.dwFileAttributes &
  263. FILE_ATTRIBUTE_DIRECTORY == 0)
  264. def is_symlink(self):
  265. return (self._find_data.dwFileAttributes &
  266. FILE_ATTRIBUTE_REPARSE_POINT != 0 and
  267. self._find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK)
  268. def inode(self):
  269. if self._inode is None:
  270. self._inode = lstat(self.path).st_ino
  271. return self._inode
  272. def __str__(self):
  273. return '<{0}: {1!r}>'.format(self.__class__.__name__, self.name)
  274. __repr__ = __str__
  275. def win_error(error, filename):
  276. exc = WindowsError(error, ctypes.FormatError(error))
  277. exc.filename = filename
  278. return exc
  279. def _scandir_python(path=unicode('.')):
  280. """Like os.listdir(), but yield DirEntry objects instead of returning
  281. a list of names.
  282. """
  283. # Call FindFirstFile and handle errors
  284. if isinstance(path, bytes):
  285. is_bytes = True
  286. filename = join(path.decode('mbcs', 'strict'), '*.*')
  287. else:
  288. is_bytes = False
  289. filename = join(path, '*.*')
  290. data = wintypes.WIN32_FIND_DATAW()
  291. data_p = ctypes.byref(data)
  292. handle = FindFirstFile(filename, data_p)
  293. if handle == INVALID_HANDLE_VALUE:
  294. error = ctypes.GetLastError()
  295. if error == ERROR_FILE_NOT_FOUND:
  296. # No files, don't yield anything
  297. return
  298. raise win_error(error, path)
  299. # Call FindNextFile in a loop, stopping when no more files
  300. try:
  301. while True:
  302. # Skip '.' and '..' (current and parent directory), but
  303. # otherwise yield (filename, stat_result) tuple
  304. name = data.cFileName
  305. if name not in ('.', '..'):
  306. if is_bytes:
  307. name = name.encode('mbcs', 'replace')
  308. yield Win32DirEntryPython(path, name, data)
  309. data = wintypes.WIN32_FIND_DATAW()
  310. data_p = ctypes.byref(data)
  311. success = FindNextFile(handle, data_p)
  312. if not success:
  313. error = ctypes.GetLastError()
  314. if error == ERROR_NO_MORE_FILES:
  315. break
  316. raise win_error(error, path)
  317. finally:
  318. if not FindClose(handle):
  319. raise win_error(ctypes.GetLastError(), path)
  320. if IS_PY3:
  321. def scandir_python(path=unicode('.')):
  322. if isinstance(path, bytes):
  323. raise TypeError("os.scandir() doesn't support bytes path on Windows, use Unicode instead")
  324. return _scandir_python(path)
  325. scandir_python.__doc__ = _scandir_python.__doc__
  326. else:
  327. scandir_python = _scandir_python
  328. if _scandir is not None:
  329. scandir_c = _scandir.scandir
  330. if _scandir is not None:
  331. scandir = scandir_c
  332. elif ctypes is not None:
  333. scandir = scandir_python
  334. else:
  335. scandir = scandir_generic
  336. # Linux, OS X, and BSD implementation
  337. elif sys.platform.startswith(('linux', 'darwin', 'sunos5')) or 'bsd' in sys.platform:
  338. have_dirent_d_type = (sys.platform != 'sunos5')
  339. if ctypes is not None and have_dirent_d_type:
  340. import ctypes.util
  341. DIR_p = ctypes.c_void_p
  342. # Rather annoying how the dirent struct is slightly different on each
  343. # platform. The only fields we care about are d_name and d_type.
  344. class Dirent(ctypes.Structure):
  345. if sys.platform.startswith('linux'):
  346. _fields_ = (
  347. ('d_ino', ctypes.c_ulong),
  348. ('d_off', ctypes.c_long),
  349. ('d_reclen', ctypes.c_ushort),
  350. ('d_type', ctypes.c_byte),
  351. ('d_name', ctypes.c_char * 256),
  352. )
  353. else:
  354. _fields_ = (
  355. ('d_ino', ctypes.c_uint32), # must be uint32, not ulong
  356. ('d_reclen', ctypes.c_ushort),
  357. ('d_type', ctypes.c_byte),
  358. ('d_namlen', ctypes.c_byte),
  359. ('d_name', ctypes.c_char * 256),
  360. )
  361. DT_UNKNOWN = 0
  362. DT_DIR = 4
  363. DT_REG = 8
  364. DT_LNK = 10
  365. Dirent_p = ctypes.POINTER(Dirent)
  366. Dirent_pp = ctypes.POINTER(Dirent_p)
  367. libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
  368. opendir = libc.opendir
  369. opendir.argtypes = [ctypes.c_char_p]
  370. opendir.restype = DIR_p
  371. readdir_r = libc.readdir_r
  372. readdir_r.argtypes = [DIR_p, Dirent_p, Dirent_pp]
  373. readdir_r.restype = ctypes.c_int
  374. closedir = libc.closedir
  375. closedir.argtypes = [DIR_p]
  376. closedir.restype = ctypes.c_int
  377. file_system_encoding = sys.getfilesystemencoding()
  378. class PosixDirEntry(object):
  379. __slots__ = ('name', '_d_type', '_stat', '_lstat', '_scandir_path', '_path', '_inode')
  380. def __init__(self, scandir_path, name, d_type, inode):
  381. self._scandir_path = scandir_path
  382. self.name = name
  383. self._d_type = d_type
  384. self._inode = inode
  385. self._stat = None
  386. self._lstat = None
  387. self._path = None
  388. @property
  389. def path(self):
  390. if self._path is None:
  391. self._path = join(self._scandir_path, self.name)
  392. return self._path
  393. def stat(self, follow_symlinks=True):
  394. if follow_symlinks:
  395. if self._stat is None:
  396. if self.is_symlink():
  397. self._stat = stat(self.path)
  398. else:
  399. if self._lstat is None:
  400. self._lstat = lstat(self.path)
  401. self._stat = self._lstat
  402. return self._stat
  403. else:
  404. if self._lstat is None:
  405. self._lstat = lstat(self.path)
  406. return self._lstat
  407. def is_dir(self, follow_symlinks=True):
  408. if (self._d_type == DT_UNKNOWN or
  409. (follow_symlinks and self.is_symlink())):
  410. try:
  411. st = self.stat(follow_symlinks=follow_symlinks)
  412. except OSError as e:
  413. if e.errno != ENOENT:
  414. raise
  415. return False
  416. return st.st_mode & 0o170000 == S_IFDIR
  417. else:
  418. return self._d_type == DT_DIR
  419. def is_file(self, follow_symlinks=True):
  420. if (self._d_type == DT_UNKNOWN or
  421. (follow_symlinks and self.is_symlink())):
  422. try:
  423. st = self.stat(follow_symlinks=follow_symlinks)
  424. except OSError as e:
  425. if e.errno != ENOENT:
  426. raise
  427. return False
  428. return st.st_mode & 0o170000 == S_IFREG
  429. else:
  430. return self._d_type == DT_REG
  431. def is_symlink(self):
  432. if self._d_type == DT_UNKNOWN:
  433. try:
  434. st = self.stat(follow_symlinks=False)
  435. except OSError as e:
  436. if e.errno != ENOENT:
  437. raise
  438. return False
  439. return st.st_mode & 0o170000 == S_IFLNK
  440. else:
  441. return self._d_type == DT_LNK
  442. def inode(self):
  443. return self._inode
  444. def __str__(self):
  445. return '<{0}: {1!r}>'.format(self.__class__.__name__, self.name)
  446. __repr__ = __str__
  447. def posix_error(filename):
  448. errno = ctypes.get_errno()
  449. exc = OSError(errno, strerror(errno))
  450. exc.filename = filename
  451. return exc
  452. def scandir_python(path=unicode('.')):
  453. """Like os.listdir(), but yield DirEntry objects instead of returning
  454. a list of names.
  455. """
  456. if isinstance(path, bytes):
  457. opendir_path = path
  458. is_bytes = True
  459. else:
  460. opendir_path = path.encode(file_system_encoding)
  461. is_bytes = False
  462. dir_p = opendir(opendir_path)
  463. if not dir_p:
  464. raise posix_error(path)
  465. try:
  466. result = Dirent_p()
  467. while True:
  468. entry = Dirent()
  469. if readdir_r(dir_p, entry, result):
  470. raise posix_error(path)
  471. if not result:
  472. break
  473. name = entry.d_name
  474. if name not in (b'.', b'..'):
  475. if not is_bytes:
  476. name = name.decode(file_system_encoding)
  477. yield PosixDirEntry(path, name, entry.d_type, entry.d_ino)
  478. finally:
  479. if closedir(dir_p):
  480. raise posix_error(path)
  481. if _scandir is not None:
  482. scandir_c = _scandir.scandir
  483. if _scandir is not None:
  484. scandir = scandir_c
  485. elif ctypes is not None:
  486. scandir = scandir_python
  487. else:
  488. scandir = scandir_generic
  489. # Some other system -- no d_type or stat information
  490. else:
  491. scandir = scandir_generic
  492. def _walk(top, topdown=True, onerror=None, followlinks=False):
  493. """Like Python 3.5's implementation of os.walk() -- faster than
  494. the pre-Python 3.5 version as it uses scandir() internally.
  495. """
  496. dirs = []
  497. nondirs = []
  498. # We may not have read permission for top, in which case we can't
  499. # get a list of the files the directory contains. os.walk
  500. # always suppressed the exception then, rather than blow up for a
  501. # minor reason when (say) a thousand readable directories are still
  502. # left to visit. That logic is copied here.
  503. try:
  504. scandir_it = scandir(top)
  505. except OSError as error:
  506. if onerror is not None:
  507. onerror(error)
  508. return
  509. while True:
  510. try:
  511. try:
  512. entry = next(scandir_it)
  513. except StopIteration:
  514. break
  515. except OSError as error:
  516. if onerror is not None:
  517. onerror(error)
  518. return
  519. try:
  520. is_dir = entry.is_dir()
  521. except OSError:
  522. # If is_dir() raises an OSError, consider that the entry is not
  523. # a directory, same behaviour than os.path.isdir().
  524. is_dir = False
  525. if is_dir:
  526. dirs.append(entry.name)
  527. else:
  528. nondirs.append(entry.name)
  529. if not topdown and is_dir:
  530. # Bottom-up: recurse into sub-directory, but exclude symlinks to
  531. # directories if followlinks is False
  532. if followlinks:
  533. walk_into = True
  534. else:
  535. try:
  536. is_symlink = entry.is_symlink()
  537. except OSError:
  538. # If is_symlink() raises an OSError, consider that the
  539. # entry is not a symbolic link, same behaviour than
  540. # os.path.islink().
  541. is_symlink = False
  542. walk_into = not is_symlink
  543. if walk_into:
  544. for entry in walk(entry.path, topdown, onerror, followlinks):
  545. yield entry
  546. # Yield before recursion if going top down
  547. if topdown:
  548. yield top, dirs, nondirs
  549. # Recurse into sub-directories
  550. for name in dirs:
  551. new_path = join(top, name)
  552. # Issue #23605: os.path.islink() is used instead of caching
  553. # entry.is_symlink() result during the loop on os.scandir() because
  554. # the caller can replace the directory entry during the "yield"
  555. # above.
  556. if followlinks or not islink(new_path):
  557. for entry in walk(new_path, topdown, onerror, followlinks):
  558. yield entry
  559. else:
  560. # Yield after recursion if going bottom up
  561. yield top, dirs, nondirs
  562. if IS_PY3 or sys.platform != 'win32':
  563. walk = _walk
  564. else:
  565. # Fix for broken unicode handling on Windows on Python 2.x, see:
  566. # https://github.com/benhoyt/scandir/issues/54
  567. file_system_encoding = sys.getfilesystemencoding()
  568. def walk(top, topdown=True, onerror=None, followlinks=False):
  569. if isinstance(top, bytes):
  570. top = top.decode(file_system_encoding)
  571. return _walk(top, topdown, onerror, followlinks)