Search code examples
pythonglobshutil

Moving all contents of a directory to another in Python


I've been trying to figure this out for hours with no luck. I have a list of directories that have subdirectories and other files of their own. I'm trying to traverse through all of them and move all of their content to a specific location. I tried shutil and glob but I couldn't get it to work. I even tried to run shell commands using subprocess.call and that also did not work either. I understand that it didn't work because I couldn't apply it properly but I couldn't find any solution that moves all contents of a directory to another.

files = glob.glob('Food101-AB/*/')
dest = 'Food-101/'

if not os.path.exists(dest):
    os.makedirs(dest)
    subprocess.call("mv Food101-AB/* Food-101/", shell=True)

    # for child in files:
    #   shutil.move(child, dest)

I'm trying to move everything in Food101-AB to Food-101


Solution

  • shutil module of the standart library is the way to go:

    >>> import shutil
    >>> shutil.move("Food101-AB", "Food-101")
    

    If you don't want to move Food101-AB folder itself, try using this:

    import shutil
    import os
    
    for i in os.listdir("Food101-AB"):
        shutil.move(os.path.join("Food101-AB", i), "Food-101")
    

    For more information about move function: https://docs.python.org/3/library/shutil.html#shutil.move