Search code examples
pythonfile-renamefile-copying

How to create multiple copies with unique names of a file and put new copies into multiple folders in Python?


Dear all please help me to clarify the way of thinking which could solve my issue.

In Python, I want to write a code that produces multiple copies with unique names (based on some rule) of a single file and put all new copies into multiple folders. I will demonstrate some picture.

A scheme of a project All the structure I created before.

And now I want to clone file "tile.png" and produce its copies as: '0.png', '1.png', and so force. These names actually based on a rule png_file_names = [j for j in range(0, 2 ** zoom)]. After I have the exact amount of copies of a file 'tile.png' with new names I want to copy them all into each subfolder: '0', '1', '2', '3' which you can see in my three.

As I understand I need to apply several loops. Thank you all! This is my code that I have for now:

def create_copies_of_a_tile (zoom):
    path_to_the_project = 'D:/ms_project'
    os.chdir(path_to_the_project)
    for j in range (0, 2**zoom):
        shutil.copy2('tile.png', '{}.png'.format(j))

Solution

  • After some trial executions I found solution:

    def create_copies_of_a_tile (zoom):
        path = 'D:/ms_project/tiles/'
        for zoom_level in range (zoom_min, zoom + 1):
            subfolders_path = os.path.join(path, str(zoom_level))
            for xtile_number in range(0, 2 ** zoom):
                sub_subfolders_path = os.path.join(subfolders_path, str(xtile_number))
                for dirpath, dirnames, files in os.walk(sub_subfolders_path):
                    os.chdir(dirpath)
                    for j in range(0, 2 ** zoom):
                        shutil.copy2('D:/ms_project/tile.png', '{}.png'.format(j))
    

    It is working, but I do not understand one thing. When I delete dirnames, files from a pre-last "for statement" for dirpath, dirnames, files in os.walk(sub_subfolders_path): (I believe I do not need that parts), I do have an error:

    TypeError: chdir: illegal type for path parameter

    Could somebody be so kind and explain to me what is going on? Thank you

    And also I was wondering if it is possible to simplify my code a bit. Thank you, all)

    And there is one more question how to apply sorting of my folders that I have on the picture? Thank you