Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: folder creation when copying files

I'm trying to create a shell script that will copy files from one computer (employee's old computer) to another (employee's new computer). I have it to the point where I can copy files over, thanks to the lovely people here, but I'm running into a problem - if I'm going from, say, this directory that has 2 files:

C:\Users\specificuser\Documents\Test Folder ....to this directory... C:\Users\specificuser\Desktop ...I see the files show up on the Desktop, but the folder those files were in (Test Folder) isn't created.

Here is the copy function I'm using:

#copy function
def dir_copy(srcpath, dstpath):
    #if the destination path doesn't exist, create it
    if not os.path.exists(dstpath):
        os.makedir(dstpath)
    #tag each file to the source path to create the file path
    for file in os.listdir(srcpath):
        srcfile = os.path.join(srcpath, file)
        dstfile = os.path.join(dstpath, file)
        #if the source file path is a directory, copy the directory
        if os.path.isdir(srcfile):
            dir_copy(srcfile, dstfile)
        else: #if the source file path is just a file, copy the file
            shutil.copyfile(srcfile, dstfile)

I know I need to create the directory on the destination, I'm just not quite sure how to do it.

Edit: I found that I had a type (os.makedir instead of os.mkdir). I tested it, and it creates directories like it's supposed to. HOWEVER I'd like it to create the directory one level up from where it's starting. For example, in Test Folder there is Sub Test Folder. It has created Sub Test Folder but won't create Test Folder because Test Folder is not part of the dstpath. Does that make sense?

like image 349
Phil Brandvold Avatar asked Nov 02 '25 01:11

Phil Brandvold


1 Answers

You might want to look at shutil.copytree(). It performs the recursive copy functionality, including directories, that you're looking for. So, for a basic recursive copy, you could just run:

shutil.copytree(srcpath, dstpath)

However, to accomplish your goal of copying the source directory to the destination directory, creating the source directory inside of the destination directory in the process, you could use something like this:

import os
import shutil

def dir_copy(srcpath, dstdir):
    dirname = os.path.basename(srcpath)
    dstpath = os.path.join(dstdir, dirname)
    shutil.copytree(srcpath, dstpath)

Note that your srcpath must not contain a slash at the end for this to work. Also, the result of joining the destination directory and the source directory name must not already exist, or copytree will fail.

like image 188
MPlanchard Avatar answered Nov 03 '25 15:11

MPlanchard