Copy by file format to another folder with Python

Blender Artists, I have a Main folder “ADAM”. ADAM contains two subfolders “A” and “B”. Subfolders A and B have different files in them also.

I am trying to write a script in blender that will

  • identify the first subfolder in main folder ADAM
  • copy all glb files in first subfolder to subfolder B

Here is my current code, but it only copies glb files from Main folder ADAM, not the first subfolder (what I want). I need help please

import bpy
import os
import shutil

SOURCE_DIR = 'C:/Users/ME/Desktop/Adam/'
DEST_DIR = 'C:/Users/ME/Desktop/Adam/B/'

def copy_glb_first_folder(SOURCE_DIR):
    folders = os.listdir(SOURCE_DIR)
    folder = folders[0]

copy_glb_first_folder(SOURCE_DIR)

for root, dirs, files in os.walk(SOURCE_DIR):
    for name in files:
        for fname in os.listdir(SOURCE_DIR):
            if fname.lower().endswith('.glb'):
                shutil.copy(os.path.join(SOURCE_DIR, fname), DEST_DIR)`Preformatted text`

Just a quick look:

  • you get the first folder by folder= folders[0]… if there is no other folder than ../B/ then this would be ../B/ … so you might wanna check… and abort if not ?
  • you aren’t using the variable folder in the following code at all…

If you don’t mind I just rewrite the code so it is easier to follow.

import os
import shutil

class FileMover:

	def movefiles(self, rootdir):
		if not os.path.exists(rootdir):
			return self.error('directory does not exist')

		dirpath_ADAM = os.path.join(rootdir, 'ADAM')
		dirpath_A = os.path.join(dirpath_ADAM, 'A')
		dirpath_B = os.path.join(dirpath_ADAM, 'B')
		for path in [dirpath_ADAM, dirpath_A, dirpath_B]:
			if not os.path.exists(path):
				return self.error(f'directory {path} not found')

		filesin_A = os.listdir(dirpath_A)
		if len(filesin_A) == 0:
			return self.error('no files found in dir A')

		for file in filesin_A:
			if os.path.splitext(file)[1] == '.txt':
				shutil.copy(os.path.join(dirpath_A, file), os.path.join(dirpath_B, file))

	def error(self, message):
		'''dummy method to merge print and return into one-liner'''
		print(message)


fm = FileMover()
fm.movefiles(r'C:\Users\const\Desktop')