85

私はPythonで/home/myUser/dir1/そのすべてのコンテンツ(およびそれらのコンテンツなど)をコピーしようとしています。/home/myuser/dir2/さらに、コピーでのすべてを上書きしたいdir2/

その仕事に適したツールのように見えますdistutils.dir_util.copy_treeが、そのような単純なタスクに使用するのがより簡単でより明白なものがあるかどうかはわかりません。

それが適切なツールである場合、どのように使用しますか?ドキュメントによると、それが取る8つのパラメータがあります。私は8つすべてを渡す必要がありますかsrcdstそしてupdate、もしそうなら、どのように(私はPythonにまったく慣れていません)。

より良いものがそこにある場合、誰かが私に例を挙げて、正しい方向に私を向けることができますか?前もって感謝します!

4

5 に答える 5

53

shutilパッケージ、特にrmtreeと を見てくださいcopytree。でファイル/パスが存在するかどうかを確認できます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)

copytreeディレクトリが既に存在する場合、ヴィンセントは機能しないという点で正しかった。より良いdistutilsバージョンも同様です。以下は の修正版ですshutil.copytreeos.makedirs()if-else-construct の後ろに置かれた最初の部分を除いて、基本的には 1 対 1 でコピーされます。

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
于 2012-10-02T09:02:48.397 に答える