Iterating Over Directory Contents
pathlib, you can also iterate over the contents of a directory. The contents of a directory are always either a subdirectory or a file, and you can iterate over them in order to do some processing on all of the contents. This could be many things.
And here you also see that what
.iterdir() returns are actually
Path objects. So, as you can see, the iterator returns
Path objects that represent all of the contents of the directory that you iterated over.
Usually you won’t have to pass the generator to the
list() function, but more commonly, you will want to do something with all of the files or directories inside of a folder, so you will use the iterator inside of a loop and then apply some sort of of processing on it.
Become a Member to join the conversation.