program story

파이썬에서 재귀 적으로 디렉토리를 복사하고 모두 덮어 쓰는 방법?

inputbox 2020. 12. 8. 08:01
반응형

파이썬에서 재귀 적으로 디렉토리를 복사하고 모두 덮어 쓰는 방법?


나는 파이썬에서 /home/myUser/dir1/모든 내용 (및 내용 등)을 복사하려고합니다 /home/myuser/dir2/. 또한 사본이 dir2/.

그것은 보이는 같은 distutils.dir_util.copy_tree작업에 적합한 도구가 될 수 있지만, 수도 같은 간단한 작업에 사용하는 것이 더 확실한 / 무엇이든 쉽게 거기하지 않도록합니다.

올바른 도구라면 어떻게 사용합니까? 문서 에 따르면 8 개의 매개 변수가 필요합니다. 나는 모든 8 단지입니다 통과해야합니까 src, dst그리고 update, 만약 그렇다면, 어떻게 (I 파이썬에 새로운 브랜드 해요).

더 나은 것이 있다면 누군가 나에게 모범을 보여주고 올바른 방향으로 나를 가리킬 수 있습니까? 미리 감사드립니다!


사용할 수 있습니다 distutils.dir_util.copy_tree. 그것은 잘 작동하고 모든 인수를 통과해야 만하지 않습니다 srcdst필수입니다.

그러나 귀하의 경우에는 shutil.copytree다르게 동작하기 때문에 유사한 도구를 사용할 수 없습니다 . 대상 디렉토리가 존재하지 않아야하므로이 함수는 내용을 덮어 쓰는 데 사용할 수 없습니다.

cp질문 주석에서 제안 된대로 도구 를 사용 하려면 os.system 함수subprocess문서 에서 볼 수 있듯이 모듈 을 사용하는 것이 현재 새 프로세스를 생성하는 데 권장되는 방법 이라는 점에 유의 하십시오 .


상기 봐 가지고 shutil, 특히, 패키지 rmtreecopytree. 파일 / 경로가 존재하는지 확인할 수 있습니다 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)

copytreeDirs가 이미 존재한다면 Vincent는 일하지 않는 것에 대해 옳았습니다 . 그래서 distutils더 좋은 버전입니다. 아래는 shutil.copytree. os.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

다음은 대상을 소스로 재귀 적으로 덮어 쓰고 필요한 디렉토리를 만드는 간단한 솔루션입니다. 이것은 심볼릭 링크를 처리하지 않지만 간단한 확장입니다 (위의 @Michael 답변 참조).

def recursive_overwrite(src, dest, ignore=None):
    if os.path.isdir(src):
        if not os.path.isdir(dest):
            os.makedirs(dest)
        files = os.listdir(src)
        if ignore is not None:
            ignored = ignore(src, files)
        else:
            ignored = set()
        for f in files:
            if f not in ignored:
                recursive_overwrite(os.path.join(src, f), 
                                    os.path.join(dest, f), 
                                    ignore)
    else:
        shutil.copyfile(src, dest)

참고 URL : https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all

반응형