README.rst 8.3 KB

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