shutil module in python :
shutil module contains a number of different file operations like copying and deleting files. But one thing we should remember that methods of this module cannot copy all file metadata . On windows, file owners, ACLs and alternate data streams will not be copied. Let’s take a look into some uses of this module :
shutil to copy all files of a directory in python 3 :
It will copy all files of ‘source_dir’ to ‘dest_dir’ :
import shutil
import os
source_dir = "/Users/codevscolor/Desktop/source"
dest_dir = "/Users/codevscolorDesktop/dest"
for file in os.listdir(source_dir):
fullpath = os.path.join(source_dir, file)
shutil.copy(fullpath,dest_dir)
shutil to move all files of a directory in python 3 :
It will move all the files of ‘source_dir’ folder to ‘dest_dir’ folder :
import shutil
import os
source_dir = "/Users/codevscolor/Desktop/source"
dest_dir = "/Users/codevscolorDesktop/dest"
for file in os.listdir(source_dir):
fullpath = os.path.join(source_dir, file)
shutil.move(fullpath,dest_dir)
shutil to copy a file using buffer :
We can use ‘shutil’ to copy a single file with a optional buffer length. The method used for this is ‘shutil.copyfileobj(fsrc, fdst[, length])‘. It will copy the contents of the object ‘fsrc’ to ‘fdst’. By default, the data is read in chunks. Example :
import shutil
import os
source_file = "/Users/codevscolor/Desktop/sourcefile.mkv"
dest_file = "/Users/codevscolor/Desktop/destfile.mkv"
buffer_size = 20
with open(source_file, 'rb') as source:
with open(dest_file, 'wb') as destination:
shutil.copyfileobj(source, destination, buffer_size)
source.close()
destination.close()
The above program will copy the ‘sourcefile.mkv’ to a new location with name ‘destfile.mkv’. The buffer size used here is 20.