Have a look at the shutil
package, especially rmtree
and copytree
. You can check if a file / path exists with os.paths.exists(<path>)
.
import shutil
import os
def copy_and_overwrite(from_path, to_path):
if os.path.exists(to_path):
shutil.rmtree(to_path)
shutil.copytree(from_path, to_path)
Vincent was right about copytree
not working, if dirs already exist. So distutils
is the nicer version. Below is a fixed version of shutil.copytree
. It's basically copied 1-1, except the first os.makedirs()
put behind an if-else-construct:
import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.isdir(dst): # This one line does the trick
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors
os.system("cp -rf /src/dir /dest/dir")
would be pretty easy... – Carisacarissacp
's docs, the-f
arg ("force"): if an existing destination file cannot be opened, remove it and try again... this doesn't seem to be the same as "overwrite all". Can you confirm it is the same and that whateverdir1
's contents are all get (recrusively) copied todir2
's subtree? Thanks again! – Unscientificcp
overwrites files by default. There's a switch that prevents it from overwriting files, but not the other way around. – Steffen