python - Comment copier des fichiers

Mots clés : pythonfilecopyfilesystemsfile-copyingpython

meilleur 4 Réponses python - Comment copier des fichiers

vote vote

92

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

82

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 
vote vote

79

import os import shutil import subprocess 
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)  # example     shutil.copyfile('source.txt', 'destination.txt') 
shutil.copy(src_file, dest_file, *, follow_symlinks=True)  # example shutil.copy('source.txt', 'destination.txt') 
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)   
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(command)   # In Linux/Unix os.system('cp source.txt destination.txt')    # In Windows os.system('copy source.txt destination.txt') 
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) 
vote vote

69

 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 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') 

Questions similaires