DESCRIPTION.rst 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. scandir, a better directory iterator and faster os.walk()
  2. =========================================================
  3. ``scandir()`` is a directory iteration function like ``os.listdir()``,
  4. except that instead of returning a list of bare filenames, it yields
  5. ``DirEntry`` objects that include file type and stat information along
  6. with the name. Using ``scandir()`` increases the speed of ``os.walk()``
  7. by 2-20 times (depending on the platform and file system) by avoiding
  8. unnecessary calls to ``os.stat()`` in most cases.
  9. Now included in a Python near you!
  10. ----------------------------------
  11. ``scandir`` has been included in the Python 3.5 standard library as
  12. ``os.scandir()``, and the related performance improvements to
  13. ``os.walk()`` have also been included. So if you're lucky enough to be
  14. using Python 3.5 (release date September 13, 2015) you get the benefit
  15. immediately, otherwise just
  16. `download this module from PyPI <https://pypi.python.org/pypi/scandir>`_,
  17. install it with ``pip install scandir``, and then do something like
  18. this in your code::
  19. # Use the built-in version of scandir/walk if possible, otherwise
  20. # use the scandir module version
  21. try:
  22. from os import scandir, walk
  23. except ImportError:
  24. from scandir import scandir, walk
  25. `PEP 471 <https://www.python.org/dev/peps/pep-0471/>`_, which is the
  26. PEP that proposes including ``scandir`` in the Python standard library,
  27. was `accepted <https://mail.python.org/pipermail/python-dev/2014-July/135561.html>`_
  28. in July 2014 by Victor Stinner, the BDFL-delegate for the PEP.
  29. This ``scandir`` module is intended to work on Python 2.6+ and Python
  30. 3.2+ (and it has been tested on those versions).
  31. Background
  32. ----------
  33. Python's built-in ``os.walk()`` is significantly slower than it needs to be,
  34. because -- in addition to calling ``listdir()`` on each directory -- it calls
  35. ``stat()`` on each file to determine whether the filename is a directory or not.
  36. But both ``FindFirstFile`` / ``FindNextFile`` on Windows and ``readdir`` on Linux/OS
  37. X already tell you whether the files returned are directories or not, so
  38. no further ``stat`` system calls are needed. In short, you can reduce the number
  39. of system calls from about 2N to N, where N is the total number of files and
  40. directories in the tree.
  41. In practice, removing all those extra system calls makes ``os.walk()`` about
  42. **7-50 times as fast on Windows, and about 3-10 times as fast on Linux and Mac OS
  43. X.** So we're not talking about micro-optimizations. See more benchmarks
  44. in the "Benchmarks" section below.
  45. Somewhat relatedly, many people have also asked for a version of
  46. ``os.listdir()`` that yields filenames as it iterates instead of returning them
  47. as one big list. This improves memory efficiency for iterating very large
  48. directories.
  49. So as well as a faster ``walk()``, scandir adds a new ``scandir()`` function.
  50. They're pretty easy to use, but see "The API" below for the full docs.
  51. Benchmarks
  52. ----------
  53. Below are results showing how many times as fast ``scandir.walk()`` is than
  54. ``os.walk()`` on various systems, found by running ``benchmark.py`` with no
  55. arguments:
  56. ==================== ============== =============
  57. System version Python version Times as fast
  58. ==================== ============== =============
  59. Windows 7 64-bit 2.7.7 64-bit 10.4
  60. Windows 7 64-bit SSD 2.7.7 64-bit 10.3
  61. Windows 7 64-bit NFS 2.7.6 64-bit 36.8
  62. Windows 7 64-bit SSD 3.4.1 64-bit 9.9
  63. Windows 7 64-bit SSD 3.5.0 64-bit 9.5
  64. CentOS 6.2 64-bit 2.6.6 64-bit 3.9
  65. Ubuntu 14.04 64-bit 2.7.6 64-bit 5.8
  66. Mac OS X 10.9.3 2.7.5 64-bit 3.8
  67. ==================== ============== =============
  68. All of the above tests were done using the fast C version of scandir
  69. (source code in ``_scandir.c``).
  70. Note that the gains are less than the above on smaller directories and greater
  71. on larger directories. This is why ``benchmark.py`` creates a test directory
  72. tree with a standardized size.
  73. The API
  74. -------
  75. walk()
  76. ~~~~~~
  77. The API for ``scandir.walk()`` is exactly the same as ``os.walk()``, so just
  78. `read the Python docs <https://docs.python.org/3.5/library/os.html#os.walk>`_.
  79. scandir()
  80. ~~~~~~~~~
  81. The full docs for ``scandir()`` and the ``DirEntry`` objects it yields are
  82. available in the `Python documentation here <https://docs.python.org/3.5/library/os.html#os.scandir>`_.
  83. But below is a brief summary as well.
  84. scandir(path='.') -> iterator of DirEntry objects for given path
  85. Like ``listdir``, ``scandir`` calls the operating system's directory
  86. iteration system calls to get the names of the files in the given
  87. ``path``, but it's different from ``listdir`` in two ways:
  88. * Instead of returning bare filename strings, it returns lightweight
  89. ``DirEntry`` objects that hold the filename string and provide
  90. simple methods that allow access to the additional data the
  91. operating system may have returned.
  92. * It returns a generator instead of a list, so that ``scandir`` acts
  93. as a true iterator instead of returning the full list immediately.
  94. ``scandir()`` yields a ``DirEntry`` object for each file and
  95. sub-directory in ``path``. Just like ``listdir``, the ``'.'``
  96. and ``'..'`` pseudo-directories are skipped, and the entries are
  97. yielded in system-dependent order. Each ``DirEntry`` object has the
  98. following attributes and methods:
  99. * ``name``: the entry's filename, relative to the scandir ``path``
  100. argument (corresponds to the return values of ``os.listdir``)
  101. * ``path``: the entry's full path name (not necessarily an absolute
  102. path) -- the equivalent of ``os.path.join(scandir_path, entry.name)``
  103. * ``is_dir(*, follow_symlinks=True)``: similar to
  104. ``pathlib.Path.is_dir()``, but the return value is cached on the
  105. ``DirEntry`` object; doesn't require a system call in most cases;
  106. don't follow symbolic links if ``follow_symlinks`` is False
  107. * ``is_file(*, follow_symlinks=True)``: similar to
  108. ``pathlib.Path.is_file()``, but the return value is cached on the
  109. ``DirEntry`` object; doesn't require a system call in most cases;
  110. don't follow symbolic links if ``follow_symlinks`` is False
  111. * ``is_symlink()``: similar to ``pathlib.Path.is_symlink()``, but the
  112. return value is cached on the ``DirEntry`` object; doesn't require a
  113. system call in most cases
  114. * ``stat(*, follow_symlinks=True)``: like ``os.stat()``, but the
  115. return value is cached on the ``DirEntry`` object; does not require a
  116. system call on Windows (except for symlinks); don't follow symbolic links
  117. (like ``os.lstat()``) if ``follow_symlinks`` is False
  118. * ``inode()``: return the inode number of the entry; the return value
  119. is cached on the ``DirEntry`` object
  120. Here's a very simple example of ``scandir()`` showing use of the
  121. ``DirEntry.name`` attribute and the ``DirEntry.is_dir()`` method::
  122. def subdirs(path):
  123. """Yield directory names not starting with '.' under given path."""
  124. for entry in os.scandir(path):
  125. if not entry.name.startswith('.') and entry.is_dir():
  126. yield entry.name
  127. This ``subdirs()`` function will be significantly faster with scandir
  128. than ``os.listdir()`` and ``os.path.isdir()`` on both Windows and POSIX
  129. systems, especially on medium-sized or large directories.
  130. Further reading
  131. ---------------
  132. * `The Python docs for scandir <https://docs.python.org/3.5/library/os.html#os.scandir>`_
  133. * `PEP 471 <https://www.python.org/dev/peps/pep-0471/>`_, the
  134. (now-accepted) Python Enhancement Proposal that proposed adding
  135. ``scandir`` to the standard library -- a lot of details here,
  136. including rejected ideas and previous discussion
  137. Flames, comments, bug reports
  138. -----------------------------
  139. Please send flames, comments, and questions about scandir to Ben Hoyt:
  140. http://benhoyt.com/
  141. File bug reports for the version in the Python 3.5 standard library
  142. `here <https://docs.python.org/3.5/bugs.html>`_, or file bug reports
  143. or feature requests for this module at the GitHub project page:
  144. https://github.com/benhoyt/scandir