파이썬에서 파일을 어떻게 복사합니까?
-
02-07-2019 - |
문제
파이썬에서 파일을 어떻게 복사합니까?
아래에서 아무것도 찾을 수 없었습니다 os
.
해결책
shutil
사용할 수있는 많은 방법이 있습니다. 그중 하나는 다음과 같습니다.
from shutil import copyfile
copyfile(src, dst)
이름이 지정된 파일의 내용을 복사하십시오 src
이름이 지정된 파일에 dst
. 목적지 위치는 쓰기 가능해야합니다. 그렇지 않으면, IOError
예외가 제기됩니다. 만약에 dst
이미 존재하면 교체됩니다. 문자 또는 블록 장치 및 파이프와 같은 특수 파일은이 기능을 복사 할 수 없습니다. src
그리고 dst
문자열로 주어진 경로 이름입니다.
다른 팁
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│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
a 예배 규칙서 (완전한 대상 파일 이름 대신),이 경우 베이스 이름 의src
새 파일을 작성하는 데 사용됩니다. - 파일 메타 데이터에서 원래 수정 및 액세스 정보 (Mtime and 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
패키지:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Function preserves supports accepts copies other permissions directory dest. file obj metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― CHUTIL.COPY ✔ ✔ ☐ ☐ shutil.copy2 ✔ ✔ ☐ ✔ chutil.copyfile ☐ ☐ ☐ ☐ chutil.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)
Python에서는 파일을 사용하여 복사 할 수 있습니다
shutil
기준 치수os
기준 치수subprocess
기준 치수
import os
import shutil
import subprocess
1) 사용 파일 복사 shutil
기준 치수
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(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
기준 치수
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(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)
디렉토리 및 파일 복사 예제 - Tim Golden의 Python Sitture에서 :
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
당신은 사용할 수 있습니다 os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
또는 내가 한 것처럼
os.system('cp '+ rawfile + ' rawdata.dat')
어디 rawfile
프로그램 내에서 생성 한 이름입니다.
이것은 Linux 전용 솔루션입니다
작은 파일과 Python 내장 만 사용하려면 다음 1 라이너를 사용할 수 있습니다.
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
아래 의견에 언급 된 @maxschlepzig가 파일이 너무 크거나 메모리가 중요한 경우 응용 프로그램에 대한 최적의 방법이 아닙니다. Swati 's 답을 선호해야합니다.
첫째, 나는 당신의 참조를 위해 Shutil 방법에 대한 철저한 치트 시트를 만들었습니다.
shutil_methods =
{'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
}
둘째, exmaples에서 복사 방법을 설명하십시오.
shutil.copyfileobj(fsrc, fdst[, length])
열린 개체 조작
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
...: shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)
복사 및 이름을 바꿉니다
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()
메타 데이터를 구제하지 않고 복사하십시오
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()
메타 데이터를 사로 잡으십시오
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
- `shutil.copytree ()``
SRC에 루팅 된 전체 디렉토리 트리를 재귀 적으로 복사하여 대상 디렉토리를 반환합니다.
큰 파일의 경우, 내가 한 일은 파일을 라인별로 읽고 각 줄을 배열로 읽었습니다. 그런 다음 배열이 특정 크기에 도달하면 새 파일에 추가하십시오.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
from subprocess import call
call("cp -p <file> <file>", shell=True)
현재 파이썬 3.5 작은 파일에 대해 다음을 수행 할 수 있습니다 (예 : 텍스트 파일, 작은 JPEG) :
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
목적지의 위치에 있던 모든 것을 덮어 쓸 것입니다
open(destination, 'wb').write(open(source, 'rb').read())
읽기 모드에서 소스 파일을 열고 쓰기 모드에서 대상 파일에 쓰십시오.
Python은 운영 체제 쉘 유틸리티를 사용하여 파일을 쉽게 복사하기위한 내장 기능을 제공합니다.
다음 명령은 파일을 복사하는 데 사용됩니다
shutil.copy(src,dst)
다음 명령은 메타 데이터 정보로 파일을 복사하는 데 사용됩니다.
shutil.copystat(src,dst)