简体   繁体   中英

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?

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)
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

import distutils.core
distutils.dir_util.copy_tree

This solved my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM