pythonshutil

Move folder contents without moving the source folder


shutil.move(src, dst) is what I feel will do the job, however, as per the Python 2 documentation:

shutil.move(src, dst) Recursively move a file or directory (src) to another location (dst).

If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.

This is a little bit different than my case as below:

Before the move: https://snag.gy/JfbE6D.jpg

shutil.move(staging_folder, final_folder)

After the move: https://snag.gy/GTfjNb.jpg

This is not what I want, I want all the content in the staging folder be moved over to under folder "final" , I don't need "staging" folder itself.


Solution

  • It turns out the path was not correct because it contains \t which was misinterpreted.

    I ended up using shutil.move + shutil.copy22

    for i in os.listdir(staging_folder):
        if not os.path.exists(final_folder):
            shutil.move(os.path.join(staging_folder, i), final_folder)
        else:
            shutil.copy2(os.path.join(staging_folder, i), final_folder)
    

    and then emptify the old folder:

    def emptify_staging(self, folder):
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                    # elif os.path.isdir(file_path): shutil.rmtree(file_path)
            except Exception as e:
                print(e)