diff --git a/Lib/http/server.py b/Lib/http/server.py
index ebc85052aecb90..8876658def6831 100644
--- a/Lib/http/server.py
+++ b/Lib/http/server.py
@@ -872,13 +872,13 @@ def list_directory(self, path):
"""
try:
- list = os.listdir(path)
+ with os.scandir(path) as it:
+ entries = sorted(it, key=lambda e: e.name.lower())
except OSError:
self.send_error(
HTTPStatus.NOT_FOUND,
"No permission to list directory")
return None
- list.sort(key=lambda a: a.lower())
r = []
displaypath = self.path
displaypath = displaypath.split('#', 1)[0]
@@ -899,15 +899,24 @@ def list_directory(self, path):
r.append(f'
{title}\n')
r.append(f'\n{title}
')
r.append('
\n')
- for name in list:
- fullname = os.path.join(path, name)
- displayname = linkname = name
+ for entry in entries:
+ displayname = linkname = entry.name
+ # Ignore any OSError raised by the os.DirEntry methods
+ # to match the behavior of their os.path.* counterpart.
+ try:
+ is_dir = entry.is_dir()
+ except OSError:
+ is_dir = False
+ try:
+ is_symlink = entry.is_symlink()
+ except OSError:
+ is_symlink = False
# Append / for directories or @ for symbolic links
- if os.path.isdir(fullname):
- displayname = name + "/"
- linkname = name + "/"
- if os.path.islink(fullname):
- displayname = name + "@"
+ if is_dir:
+ displayname = entry.name + "/"
+ linkname = entry.name + "/"
+ if is_symlink:
+ displayname = entry.name + "@"
# Note: a link to a directory displays with @ and links with /
r.append('- %s
'
% (urllib.parse.quote(linkname,
diff --git a/Misc/NEWS.d/next/Library/2026-06-20-09-00-26.gh-issue-151788.Gr8IxK.rst b/Misc/NEWS.d/next/Library/2026-06-20-09-00-26.gh-issue-151788.Gr8IxK.rst
new file mode 100644
index 00000000000000..135d1b944d1c0a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-06-20-09-00-26.gh-issue-151788.Gr8IxK.rst
@@ -0,0 +1,4 @@
+:class:`http.server.SimpleHTTPRequestHandler` now relies on :func:`os.scandir`
+instead of :func:`os.listdir` to build directory listings, thereby reducing
+the total number of :func:`os.stat` calls per entry. This typically improves
+directory listing performance on filesystems where such calls are slow.