How to copy a file along with directory structure/path using python?

PythonFileDirectoryCopy

Python Problem Overview


First thing I have to mention here, I'm new to python.

Now I have a file located in:

a/long/long/path/to/file.py

I want to copy to my home directory with a new folder created:

/home/myhome/new_folder

My expected result is:

/home/myhome/new_folder/a/long/long/path/to/file.py

Is there any existing library to do that? If no, how can I achieve that?

Python Solutions


Solution 1 - Python

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Solution 2 - Python

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJs LimView Question on Stackoverflow
Solution 1 - PythonjfsView Answer on Stackoverflow
Solution 2 - PythonewokView Answer on Stackoverflow