IKA
IKA

Reputation: 161

Python move and overwrite folder without delete destination folder content

I need move folder and it's content from dir1 to dir2. Dir2 contains files which I do not want to delete . How to achieve this?

Upvotes: 0

Views: 2109

Answers (3)

IKA
IKA

Reputation: 161

import distutils.core
distutils.dir_util.copy_tree

This solved my problem.

Upvotes: 0

Andy Novocin
Andy Novocin

Reputation: 454

import os
os.system('mv /path/to/d1 /path/to/d2')

Works if you have a *nix shell and want the entire folder moved over.

import os
os.rename('d1', 'd2/d1')

Otherwise

Upvotes: 0

user2497586
user2497586

Reputation:

Use the shutil package.

It's a package that allows you to do anything with files. The only caveat, which you should expect, is that if you move a file from dir1 to dir2, and there is a file with the same name in dir2, that file will be deleted.

It's possible that you could do a check to see if there exists a file in dir2 before you do the move. Then, you could either abort the move or change the name of file in dir2 before you do the move. Either way works.

This is the code

shutil.move(src, dst)

Upvotes: 3

Related Questions