bayman
bayman

Reputation: 1719

Python3 how to get current and next directory from os.walk?

How do I traverse through a directory and print out the current directory and the next directory in the iteration?

currentdir = '/tmp/test'
for root, dirs, files in os.walk(currentdir):
    print("Current dir: {}: ".format(root))
    print("Next dir: {}: ".format(next(os.walk(root))))

Upvotes: 1

Views: 4505

Answers (2)

FHTMitchell
FHTMitchell

Reputation: 12147

Like so

currentdir = '/tmp/test'
itr = iter(os.walk(currentdir))
root, dirs, files = next(itr)  # get first element

for next_root, next_dirs, next_files in itr:  # get second element onwards
    print("Current dir: {}: ".format(root))
    print("Next dir: {}: ".format(next_root))
    root, dirs, files = next_root, next_dirs, next_files

Upvotes: 3

Gelineau
Gelineau

Reputation: 2090

os.walk returns an iterator, that can be run only once.

If memory is not an issue, you can put the results into a list, and then iterate over the list:

roots = [root for root, _, _ in os.walk(current_dir)]

for root, next_root in zip(roots, roots[1:]):
    print(root, "next = ", next_root)

# and if you need the last one
print(roots[-1], "last one - no next")

If memory is an issue, you can use itertools.tee and itertools.islice to manipulate the iterators, but in this case, FHTMitchell's answer would be easier to read in my opinion.

Upvotes: 1

Related Questions