File tree Expand file tree Collapse file tree 1 file changed +17
-14
lines changed Expand file tree Collapse file tree 1 file changed +17
-14
lines changed Original file line number Diff line number Diff line change @@ -957,23 +957,26 @@ def scandir(
957
957
The default is to sort by name.
958
958
If the directory does not exist, return an empty list.
959
959
"""
960
+ entries = []
961
+ # Attempt to create a scandir iterator for the given path.
960
962
try :
961
- entries = []
962
- with os .scandir (path ) as s :
963
- # Skip entries with symlink loops and other brokenness, so the caller
964
- # doesn't have to deal with it.
965
- for entry in s :
966
- try :
967
- entry .is_file ()
968
- except OSError as err :
969
- if _ignore_error (err ):
970
- continue
971
- raise
972
- entries .append (entry )
973
- entries .sort (key = sort_key ) # type: ignore[arg-type]
974
- return entries
963
+ scandir_iter = os .scandir (path )
975
964
except FileNotFoundError :
965
+ # If the directory does not exist, return an empty list.
976
966
return []
967
+ # Use the scandir iterator in a context manager to ensure it is properly closed.
968
+ with scandir_iter as s :
969
+ for entry in s :
970
+ try :
971
+ entry .is_file ()
972
+ except OSError as err :
973
+ if _ignore_error (err ):
974
+ continue
975
+ # Reraise non-ignorable errors to avoid hiding issues.
976
+ raise
977
+ entries .append (entry )
978
+ entries .sort (key = sort_key ) # type: ignore[arg-type]
979
+ return entries
977
980
978
981
979
982
def visit (
You can’t perform that action at this time.
0 commit comments