0

It's my understanding that path objects do not support slicing in Python. When implementing the concrete Path object, iterdir(), a long sequence of directories are returned. How can I reduce the number of directories returned by the iterdir() function? Suppose, I intend on printing only half of the Windows directories. The following code is as near as I could get to "slicing" the iterdir() function to print only 5 directories.

import pathlib

Dir = pathlib.Path(r'\Windows')

for paths in Dir.iterdir():
                                                                              
    print(paths[0:6])

This code returns:

Traceback (most recent call last):
File "C:/Users/charles/OneDrive/Oak.py", line 133, in <module>
print(paths[0:6])
TypeError: 'WindowsPath' object is not subscriptable

Now, let's try implementing the itertools islice() function. Please correct me if my code is not syntactically correct. Bear with me I am a beginner.

import itertools

for paths in itertools.islice(Dir, 0, 6):
    print(paths)

"Slicing" the iterdir() function is of zero urgency, it's just that the amount of directories iterdir() would print without slicing is too overwhelming.

martineau
  • 119,623
  • 25
  • 170
  • 301
Charles
  • 15
  • 3
  • Have you looked at `itertools.islice()`? – Grismar Jul 19 '22 at 23:49
  • 1
    Since the order that [`iterdir()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir) yields the path objects of the directory is arbitrary, slicing them would hardly ever be useful even if it were possible to do directly — your hypothetical use case notwithstanding. – martineau Jul 20 '22 at 00:07
  • 1
    `for paths in itertools.islice(Dir.iterdir(), 6):` is what you wanted. You still need the `.iterdir()` to create the iterator, `islice` just takes an existing iterator and slices down the output lazily. – ShadowRanger Jul 20 '22 at 00:12
  • Also note that you could use a counter to stop the `for` loop after a certain number of paths have been printed. You can terminate a loop early via a `break` statement. This isn't especially "pythonic" but it would work (and sounds OK given for your current skill level). – martineau Jul 20 '22 at 00:51

0 Answers0