파일을 복사하는 방법?


질문

 

파이썬에서 파일을 복사하려면 어떻게합니까?


답변

 

Shutil은 당신이 사용할 수있는 많은 방법을 가지고 있습니다.그 중 하나는 다음과 같습니다.

import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)  # dst can be a folder; use shutil.copy2() to preserve timestamp

SRC라는 파일의 내용을 DST라는 파일로 복사하십시오.SRC와 DST는 모두 경로를 포함하여 파일의 전체 파일 이름이어야합니다. 대상 위치는 쓸 수 있어야합니다.그렇지 않으면 IoError 예외가 발생합니다. DST가 이미 존재하면 교체됩니다. 문자 또는 블록 장치 및 파이프와 같은 특수 파일은이 기능으로 복사 할 수 없습니다. 복사본을 사용하면 SRC와 DST가 STRS로 지정된 경로 이름입니다.

쳐다 보는 또 다른 shutil 방법은 shutil.copy2 ()입니다.그것은 비슷하지만 더 많은 메타 데이터 (예 : 타임 스탬프)를 보존합니다.

OS.Path 작업을 사용하는 경우 CopyFile이 아닌 복사본을 사용하십시오.CopyFile은 문자열 만 사용할 수 있습니다.



답변

Function Copies
metadata
Copies
permissions
Uses file object Destination
may be directory
shutil.copy No Yes No Yes
shutil.copyfile No No No No
shutil.copy2 Yes Yes No Yes
shutil.copyfileobj No No Yes No


답변

Copy2 (Src, DST)는 종종 CopyFile (SRC, DST)보다 더 유용합니다.

DST는 DST가 디렉토리 (완전한 대상 파일 이름 대신)를 허용합니다.이 경우 SRC의 기본 파일이 새 파일을 만드는 데 사용됩니다. 파일 메타 데이터의 원래 수정 및 액세스 정보 (MTIME 및 ATIME)를 보존합니다 (그러나 이것은 약간의 오버 헤드와 함께 제공됩니다).

다음은 짧은 예입니다.

import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext


답변

파이썬에서는 파일을 복사 할 수 있습니다

shutil 모듈 OS 모듈 서브 프로세스 모듈


import os
import shutil
import subprocess

1) Shutil 모듈을 사용하여 파일을 복사합니다

shutil.CopyFile 서명

shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

# example    
shutil.copyfile('source.txt', 'destination.txt')

shutil.copy 서명

shutil.copy(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy('source.txt', 'destination.txt')

shutil.copy2 서명

shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy2('source.txt', 'destination.txt')  

shutil.copyfileobj 서명

shutil.copyfileobj(src_file_object, dest_file_object[, length])

# example
file_src = 'source.txt'  
f_src = open(file_src, 'rb')

file_dest = 'destination.txt'  
f_dest = open(file_dest, 'wb')

shutil.copyfileobj(f_src, f_dest)  

2) OS 모듈을 사용하여 파일을 복사합니다

OS.Popen 서명

os.popen(cmd[, mode[, bufsize]])

# example
# In Unix/Linux
os.popen('cp source.txt destination.txt') 

# In Windows
os.popen('copy source.txt destination.txt')

OS.System 서명

os.system(command)


# In Linux/Unix
os.system('cp source.txt destination.txt')  

# In Windows
os.system('copy source.txt destination.txt')

3) 서브 프로세스 모듈을 사용하여 파일 복사

subprocess.call 서명

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True) 

# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)

subprocess.check_output 서명

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)

# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)



답변

Shutil 패키지에서 복사 기능 중 하나를 사용할 수 있습니다.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata  
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy              ✔             ✔                 ☐           ☐
shutil.copy2             ✔             ✔                 ☐           ✔
shutil.copyfile          ☐             ☐                 ☐           ☐
shutil.copyfileobj       ☐             ☐                 ✔           ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

예시:

import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')


답변

파일을 복사하는 것은 아래의 예제에 의해 표시된 바와 같이 상대적으로 간단한 작업이지만 대신 Shutil STDLIB 모듈을 사용해야합니다.

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

파일 이름으로 복사하려는 경우 다음과 같이 할 수 있습니다.

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)
출처:https://stackoverflow.com/questions/123198/how-to-copy-files