简体   繁体   中英

How to copy all subfolders into an existing folder in Python 3?

I am sure I am missing this, as it has to be easy, but I have looked in Google, The Docs, and SO and I can not find a simple way to copy a bunch of directories into another directory that already exists from Python 3?

All of the answers I find recommend using shutil.copytree but as I said, I need to copy a bunch of folders, and all their contents, into an existing folder (and keep any folders or that already existed in the destination)

Is there a way to do this on windows?

I would look into using the os module built into python. Specifically os.walk which returns all the files and subdirectories within the directory you point it to. I will not just tell you exactly how to do it, however here is some sample code that i use to backup my files. I use the os and zipfile modules.

import zipfile
import time
import os

def main():
    date = time.strftime("%m.%d.%Y")

    zf = zipfile.ZipFile('/media/morpheous/PORTEUS/' + date, 'w')

    for root, j, files in os.walk('/home/morpheous/Documents'):
        for i in files:
            zf.write(os.path.join(root, i))
zf.close()

Hope this helps. Also it should be pointed out that i do this in linux, however with a few changes to the file paths it should work the same

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