recursive python; copy files, directories and set ownership

Hi, today I want to post a small script to copy files and directories and add a specific owner to a folder. I did this script myself and I am fairly new to python, about 6 months of experience. If you think it should be changed or has issues, please let me know so I can improve it.
To achieve my objective I have used a few standard libraries that come already with any major python distribution (`os`, `shutil`, `pwd`, `grp`; I will talk about those in a bit more details afterwards). Then I created a function `copy_files`. This function can receive the source files path, the destination, owner and space, this parameters are used to copy the files set owner and show the results. In this function I use recursion as this is a classic recursion problem, I will come back to this further on this post. The last part of the script checks is the destination exists actually calls copy_files function. This is the code:

import os
import shutil
import pwd
import grp


# Copy the files function
def copy_files(source, destination, username, space=''):
    # Os chown of the config folder
    """
    :rtype: object
    """
    uid = pwd.getpwnam(username).pw_uid
    gid = grp.getgrnam(username).gr_gid
    files = os.listdir(source)
    files.sort()
    os.chown(destination, uid, gid)
    for f in files:
        src = source + '/' + f
        dst = destination + '/' + f
        if os.path.isdir(src) == True:
            print space + '- ' + src
            try:
                os.stat(dst)
                os.chown(dst, uid, gid)
            except:
                os.mkdir(dst)
                os.chown(dst, uid, gid)
            copy_files(src, dst, username, '  ')
        else:
            print space + '|__' + src
            shutil.copy(src, dst)
            os.chown(dst, uid, gid)


destination_code_path = '/var/lib/nc-backup-py'
try:
    os.stat(destination_code_path)
except:
    os.mkdir(destination_code_path)

# Call function.
copy_files('/home/test/folder', destination_code_path, 'sample_user')

 

That is pretty much for today.

Leave a Reply

Your email address will not be published. Required fields are marked *