programing

Python에서 파일 또는 디렉토리를 재귀적으로 복사

mytipbox 2023. 7. 17. 23:06
반응형

Python에서 파일 또는 디렉토리를 재귀적으로 복사

Python은 파일을 복사하는 기능(예:shutil.copy) 및 디렉터리 복사 기능(예:shutil.copytree) 하지만 둘 다 처리할 수 있는 기능을 찾지 못했습니다.물론 파일을 복사할지 디렉터리를 복사할지 확인하는 것은 사소한 일이지만, 이상한 누락인 것 같습니다.

유닉스처럼 작동하는 표준 기능이 정말로 없습니까?cp -r명령, 즉 디렉터리와 파일 및 복사본을 모두 지원합니까?파이썬에서 이 문제를 해결하는 가장 우아한 방법은 무엇입니까?

먼저 전화를 걸어보고 예외가 발생한 경우 를 사용하여 다시 시도해 보는 것이 좋습니다.

import shutil, errno

def copyanything(src, dst):
    try:
        shutil.copytree(src, dst)
    except OSError as exc: # python >2.5
        if exc.errno in (errno.ENOTDIR, errno.EINVAL):
            shutil.copy(src, dst)
        else: raise

Tzot 및 gns 답변을 추가하기 위해 파일 및 폴더를 재귀적으로 복사하는 다른 방법이 있습니다(Python 3).X)

import os, shutil

root_src_dir = r'C:\MyMusic'    #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp'  #Path to the destination folder

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, dst_dir)

처음이신데 파일과 폴더를 재귀적으로 복사하는 방법을 모르신다면 도움이 되었으면 합니다.

shutil.copy그리고.shutil.copy2파일을 복사하고 있습니다.

shutil.copytree모든 파일 및 모든 하위 폴더가 포함된 폴더를 복사합니다. shutil.copytree사용 중shutil.copy2파일을 복사합니다.

그래서 와 유사합니다.cp -r당신이 말하는 것은shutil.copytree왜냐면cp -r폴더 및 해당 파일/하위 폴더를 대상으로 복사합니다.shutil.copytree다음을 제외하고는-r cp파일 복사shutil.copy그리고.shutil.copy2하다, 하다, 하다, 하다, 하다, 하다, 하다, 하다, 하다, 나다

지금까지 찾은 가장 빠르고 우아한 방법은 distutils.dir_util native package의 copy_tree 함수를 사용하는 것입니다.

import distutils.dir_util
from_dir = "foo/bar"
to_dir = "truc/machin"
distutils.dir_util.copy_tree(from_dir, to_dir)

유닉스cp디렉터리와 파일을 모두 지원하지 않음:

betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).

cp가 디렉토리를 복사하도록 하려면 '-r' 플래그를 사용하여 수동으로 cp에게 디렉토리라고 말해야 합니다.

하지만 여기에는 단절이 있습니다.cp -r파일 이름을 전달하면 소스가 단일 파일만 복사하고 복사 트리는 복사하지 않습니다.

python shutil.copytree 메서드가 엉망입니다.올바르게 작동하는 작업을 수행했습니다.

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

언급URL : https://stackoverflow.com/questions/1994488/copy-file-or-directories-recursively-in-python

반응형