Move the entire folder in Python

Source: Internet
Author: User

The latest project is to move the entire folder in one directory to another directory. The folder contains many layers of folders, and the most rare one is that if there are folders with the same name under different folders, move them to the same directory, you must integrate all the contents of folders with the same name. For example:

Directory D contains the following content: (D:/src/)
D:/src/B/)

Directory E:/DST

To add the contents in the D:/src/a folder (including folders and files), D:/src/B/A (including folders and files)

(Note: There may be files with the same name under the folder)

Move to E:/DST

You can write a function to implement the above functions:

Def
Movedirandfiles (srcpath, dstpath)


Allchangefilelist = OS. listdir (srcpath)


For changefileitem in allchangefilelist:


Changefilepath = OS. Path. Join (srcpath, changefileitem)


If OS. Path. isdir (changefilepath ):


Dstaddpath = OS. Path. Join. (dstpath, changefileitem)


If OS. Path. Exits (dstaddpath ):


Movedirandfiles (changefilepath, dstaddpath)


Else:


Shutil. copytree (changefilepath, dstaddpath, false)


Shutil. retree (changefilepath)


Else:


Shutil. Move (changefilepath, dstpath)


OS. rmdir (srcpath)


Return ture

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.