3

I'm currently writing a python script which you can give a drive or folder, and it then iterates through every image on the drive or folder and moves them all into one folder.

My issue is that using os.walk, it isn't opening the subdirs automatically. As an example, say I chose the E: drive to scan. E: drives file structure;

E:
   + Folder1
       - file.png
       - file2.png
   - files.jpg

The only file that my script will detect is files.jpg, as the other files are nested in a subdir, which os.walk does not open and check for files.

Here's the code I'm using as of right now;

# For each file in the drive
    for folders, sub_folders, files in os.walk(drive):
        # For each name in the files
        for filename in files:
            if filename == drive + "\\ImageSorter\\":
                continue

            file_name = os.path.splitext(filename)[0]
            extension = os.path.splitext(filename)[1]

Is there a way to get os.walk to iterate through all subdirs on the drive, rather than just the first folder?

siroot
  • 193
  • 1
  • 2
  • 9
  • 1
    You need to loop over the sub folders too. - https://www.tutorialspoint.com/python/os_walk.htm – Chen A. Jun 04 '18 at 06:48

1 Answers1

0

Try this code

import os
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)
Abhisek Roy
  • 582
  • 12
  • 31