development

Python에서 여러 파일 복사

big-blog 2020. 10. 16. 07:36
반응형

Python에서 여러 파일 복사


Python을 사용하여 한 디렉터리에있는 모든 파일을 다른 디렉터리로 복사하는 방법. 소스 경로와 대상 경로가 문자열로 있습니다.


os.listdir ()사용 하여 소스 디렉토리에서 파일을 가져 오고 os.path.isfile () 을 사용하여 일반 파일 (* nix 시스템의 심볼릭 링크 포함)인지 확인하고 shutil.copy 를 사용하여 복사를 수행 할 수 있습니다.

다음 코드는 원본 디렉터리의 일반 파일 만 대상 디렉터리로 복사합니다 (하위 디렉터리를 복사하지 않으려 고 가정합니다).

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

전체 트리 (하위 디렉토리 등)를 복사하지 않으려면 또는를 사용 glob.glob("path/to/dir/*.*")하여 모든 파일 이름 목록을 가져 오고 목록을 반복하여 shutil.copy각 파일을 복사 하는 사용 하십시오.

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)

Python 문서 , 특히 copytree 명령 에서 shutil을 살펴보십시오 .


import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source  to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise skip if file exist
:return: count of copied files
"""
files_count = 0
if not os.path.exists(destination_path):
    os.mkdir(destination_path)
items = glob.glob(source_path + '/*')
for item in items:
    if os.path.isdir(item):
        path = os.path.join(destination_path, item.split('/')[-1])
        files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
    else:
        file = os.path.join(destination_path, item.split('/')[-1])
        if not os.path.exists(file) or override:
            shutil.copyfile(item, file)
            files_count += 1
return files_count

다음은이 문제를 해결하는 데 사용한 디렉토리 (하위 디렉토리 포함)의 내용을 한 번에 하나씩 복사 할 수있는 재귀 복사 기능의 또 다른 예입니다.

import os
import shutil

def recursive_copy(src, dest):
    """
    Copy each file from src dir to dest dir, including sub-directories.
    """
    for item in os.listdir(src):
        file_path = os.path.join(src, item)

        # if item is a file, copy it
        if os.path.isfile(file_path):
            shutil.copy(file_path, dest)

        # else if item is a folder, recurse 
        elif os.path.isdir(file_path):
            new_dest = os.path.join(dest, item)
            os.mkdir(new_dest)
            recursive_copy(file_path, new_dest)

편집 : 할 수 있다면 확실히 shutil.copytree(src, dest). 그래도 대상 폴더가 존재하지 않아야합니다. 기존 폴더에 파일을 복사해야하는 경우 위의 방법이 잘 작동합니다!

참고 URL : https://stackoverflow.com/questions/3397752/copy-multiple-files-in-python

반응형