Move child folder contents to parent folder in python

后端 未结 4 862
走了就别回头了
走了就别回头了 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 06:46

    Example using the os and shutil modules:

    from os.path import join
    from os import listdir, rmdir
    from shutil import move
    
    root = 'dstfolder/slave1'
    for filename in listdir(join(root, 'slave')):
        move(join(root, 'slave', filename), join(root, filename))
    rmdir(root)
    
    0 讨论(0)
  • 2021-01-05 06:50

    Maybe you could get into the dictionary slave, and then

    exec system('mv .........')
    

    It will work won't it?

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 07:08

    The problem might be with the path you specified in the shutil.move function

    Try this code

    import os
    import shutil
    for r,d,f in os.walk("slave1"):
        for files in f:
            filepath = os.path.join(os.getcwd(),"slave1","slave", files)
            destpath = os.path.join(os.getcwd(),"slave1")
            shutil.copy(filepath,destpath)
    
    shutil.rmtree(os.path.join(os.getcwd(),"slave1","slave"))
    

    Paste it into a .py file in the dstfolder. I.e. slave1 and this file should remain side by side. and then run it. worked for me

    0 讨论(0)
提交回复
热议问题