Python - Move and overwrite files and folders

后端 未结 6 1956
情话喂你
情话喂你 2021-01-30 06:27

I have a directory, \'Dst Directory\', which has files and folders in it and I have \'src Directory\' which also has files and folders in it. What I want to do is move the conte

6条回答
  •  [愿得一人]
    2021-01-30 06:54

    I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.

    I solved it by using os.walk(), recursively calling my function and using shutil.move() on files which I wanted to overwrite and folders which did not exist.

    It works like shutil.move(), but with the benefit that existing files are only overwritten, but not deleted.

    import os
    import shutil
    
    def moverecursively(source_folder, destination_folder):
        basename = os.path.basename(source_folder)
        dest_dir = os.path.join(destination_folder, basename)
        if not os.path.exists(dest_dir):
            shutil.move(source_folder, destination_folder)
        else:
            dst_path = os.path.join(destination_folder, basename)
            for root, dirs, files in os.walk(source_folder):
                for item in files:
                    src_path = os.path.join(root, item)
                    if os.path.exists(dst_file):
                        os.remove(dst_file)
                    shutil.move(src_path, dst_path)
                for item in dirs:
                    src_path = os.path.join(root, item)
                    moverecursively(src_path, dst_path)
    

提交回复
热议问题