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.