Move child folder contents to parent folder in python

后端 未结 4 893
走了就别回头了
走了就别回头了 2021-01-05 06:27

I have a specific problem in python. Below is my folder structure.

dstfolder/slave1/slave

I want the contents of \'slave\' folder to

4条回答
  •  青春惊慌失措
    2021-01-05 07:03

    I needed something a little more generic, i.e. move all the files from all the [sub]+folders into the root folder.

    For example start with:

    root_folder
    |----test1.txt
    |----1
         |----test2.txt
         |----2
              |----test3.txt
    

    And end up with:

    root_folder
    |----test1.txt
    |----test2.txt
    |----test3.txt
    

    A quick recursive function does the trick:

    import os, shutil, sys 
    
    def move_to_root_folder(root_path, cur_path):
        for filename in os.listdir(cur_path):
            if os.path.isfile(os.path.join(cur_path, filename)):
                shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename))
            elif os.path.isdir(os.path.join(cur_path, filename)):
                move_to_root_folder(root_path, os.path.join(cur_path, filename))
            else:
                sys.exit("Should never reach here.")
        # remove empty folders
        if cur_path != root_path:
            os.rmdir(cur_path)
    

    You will usually call it with the same argument for root_path and cur_path, e.g. move_to_root_folder(os.getcwd(),os.getcwd()) if you want to try it in the python environment.

提交回复
热议问题