답변:
먼저을 호출 shutil.copytree하고 예외가 발생하면를 사용하여 다시 시도하십시오 shutil.copy.
import shutil, errno
def copyanything(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else: raise
shutil.copytree앞으로 두 경우 모두 기능을 개선하고 관리하는 것을 막을 수있는 것은 없습니다 . 4) 예외는 파이썬에서 그다지 예외적이지 않습니다. 예를 들어, 반복은 StopIteration 예외를 발생시켜 중지합니다.
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합니다.
shutil.copytree('C:\myfile.txt', 'C:\otherfile'). 작동하지 않습니다. 그게 OP가 요구했던 것입니다 ... 7 년 전.
Unix cp는 '디렉토리와 파일을 모두 지원'하지 않습니다.
betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).
cp가 디렉토리를 복사하도록하려면 '-r'플래그를 사용하여 cp에게 디렉토리임을 수동으로 알려야합니다.
하지만 여기에 약간의 연결이 끊어졌습니다 cp -r. 소스가 파일 이름을 전달하면 행복하게 단일 파일 만 복사합니다. 카피 트리는 그렇지 않습니다.
파이썬 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('..')
copytree단일 파일을 복사 할 수 있도록 Python 버그 추적기에 개선 요청을 제출할 수 있습니까?