'Flattening Directory tree in Google Colab

I have a tree of directories like this

User-1

Raw

--Scan1.img

--Scan2.img

User-2

RAW

--Scan1.img

--Scan2.img

Etc

How would I go about flattening the directory so that I instead had a single folder of files such as User1/Scan1.img, User1/Scan2.img, etc

I tried using the following code to copy and rename the files, however it does gives me errors actually running it:

import glob
import shutil
import os
RootDir1 = r'/content/drive/MyDrive/OASIS2/OAS2_RAW_PART1'
TargetFolder = r'/content/drive/MyDrive/OASIS2/OASIS CONSOLIDATED'
for root, dirs, files in os.walk((os.path.normpath(RootDir1)), topdown=False):
        for name in files:
            if name.endswith('.img'):
                src_dir = os.path.normpath(RootDir1) 
                SourceFolder = os.path.join(root,name)
                print (TargetFolder + root + name)
                shutil.copy2(SourceFolder, TargetFolder) #copies csv to new folder
                os.rename(TargetFolder + '/' + name, TargetFolder + root + '/' + name)

Thank you for your assistance.



Solution 1:[1]

The program that I created to flatten the directory tree looked like this:

import glob
import shutil
import os
from pathlib import Path
RootDir1 = r'/content/drive/MyDrive/OASIS2/OAS2_RAW_PART_HOLD'
TargetFolder = r'/content/drive/MyDrive/OASIS2/OASIS CONSOLIDATED'
for root, dirs, files in os.walk((os.path.normpath(RootDir1)), topdown=False):
        for name in files:
            if name.endswith('.img'):
                src_dir = os.path.normpath(RootDir1) 
                SourceFolder = os.path.join(root,name)
                person = Path(SourceFolder).parts[6]
                listOfStrings = [person,'-' , name]
                fileString = "".join(listOfStrings)
                print(fileString)
                #print(os.path.split(os.path.dirname(SourceFolder))[-2])
                #print (TargetFolder + root + name)
                shutil.move(SourceFolder,os.path.join(TargetFolder,fileString))
                #SourceFolder = os.path.join(root,name)

                #shutil.copy2(SourceFolder, TargetFolder) #copies csv to new folder

And accomplished the problem

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johnney