Search code examples
pythondirectorysubdirectorydirectory-structuredistutils

Python: copying files group to subdirectories


I'm working with Python and I'd like to copy 3 files of a certain folder /Users/jake/Desktop/exp to all the subfolders of other sub-directories belonging to the directory /toyspace:

/Users/jake/Desktop/toyspace/1A/AAA
/Users/jake/Desktop/toyspace/1A/BBB
/Users/jake/Desktop/toyspace/1A/CCC

/Users/jake/Desktop/toyspace/2B/AAA
/Users/jake/Desktop/toyspace/2B/BBB
/Users/jake/Desktop/toyspace/2B/CCC

So the subfolders names are the same for all the sub-directories. I wrote something like that:

from distutils.dir_util import copy_tree

def myfunc (source, destination):

    fromDirectory = source
    toDirectory = destination

    copy_tree(fromDirectory, toDirectory)

    for subfold in toDirectory:
        myfunc(fromDirectory, subfold)

Where source =/Users/jake/Desktop/exp and destination =/Users/jake/Desktop/toyspace, but it returns me an error:

DistutilsFileError: could not create '/motif_list.txt': Read-only file system

Can you help me? Thanks in advance!


Solution

  • Unfortunately I have not used distutils but you can try to automate using the os command as below

    import os
    def copy_folders(source_dir, destination_dir):
        files = os.listdir(source_dir)
        for sub_folder1 in os.listdir(destination_dir):
            for sub_folder in os.listdir(destination_dir + sub_folder1 + '/'):
                for file in files:
                    os.system('cp ' + source_dir + file + ' ' + destination_dir + sub_folder1 + '/' + sub_folder + '/')
    

    Let me know how it goes :)