1

I am able to get a script that will iterate over all files and folders:

    for root, folders, filenames in os.walk(FOLDER_TO_UPLOAD):
        for folder in sorted(folders):
            path = os.path.normpath(os.path.join(root, folder))
            print(path)
        for file in filenames:
            path = os.path.normpath(os.path.join(root, file))
            if os.path.isfile(path):
                print(path)

For what I am trying to do, the problem is that when I find a folder, I need to finish with all the contents of that folder and its subfolders before moving to the next item in the list. I think I need to place some kind of recursion in the current script, but I suck at recursion, and not sure if that is the correct approach.

The goal is that if my folder structure is like so:

| - A
| - - B, file.txt
| - - -C
| - - D

iterate over the above should yield:

- A
- A/B
- A/B/file.txt
- A/B/C
- A/D

Currently, I am getting:

- A
- A/B
- A/D
- A/B/C
- A/B/file.txt

I need the output to be exactly as if I were to look in a folder on my OS and starting at the first item, look at everything in there iteratively (meaning look inside the subfolder's first item) before looking at the second item). Meaning, the exact order of files/folders as they appear in the OS.

3
  • I'm not perfectly clear on what you're after, but you may want to look into topdown vs bottomup (default) scanning as described in the docs for os.walk.
    – theherk
    Commented Sep 15, 2023 at 20:14
  • 1
    I updated the question to be more clear on what the result should be
    – kravb
    Commented Sep 15, 2023 at 21:05
  • 1
    You're definitely looking for os.walk() , you need to manipulate the output to obtain the structure you want, but it will perform the algorithm that you want (recursively scanning all subdirectories) Commented Sep 15, 2023 at 21:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.