Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Answer

Post Timeline

Commonmark migration
Source Link

###1) Copying files using shutil module

1) Copying files using shutil module

###2) Copying files using os module

2) Copying files using os module

###3) Copying files using subprocess module

3) Copying files using subprocess module

###1) Copying files using shutil module

###2) Copying files using os module

###3) Copying files using subprocess module

1) Copying files using shutil module

2) Copying files using os module

3) Copying files using subprocess module

Post Undeleted by Jean-François Fabre
Post Deleted by Jean-François Fabre
Source Link
kmario23
  • 62.1k
  • 17
  • 174
  • 160

In Python, you can copy the files using


import os
import shutil
import subprocess

###1) Copying files using shutil module

shutil.copyfile signature

shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example 
shutil.copyfile('source.txt', 'destination.txt')

shutil.copy signature

shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')

shutil.copy2 signature

shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt') 

shutil.copyfileobj signature

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) Copying files using os module

os.popen signature

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 signature

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

###3) Copying files using subprocess module

subprocess.call signature

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 signature

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)

lang-py

AltStyle によって変換されたページ (->オリジナル) /