Home »
Python
Copy all files from a directory to another in Python
Here, we are going to learn how to copy all files from a directory to another directory in Python using shutil module?
Submitted by Sapna Deraje Radhakrishna, on September 30, 2019
shutil (shell utilities) module, provides option to copy the files recursively from src to dst.
The syntax to copy all files is:
shutil.copytree(
src,
dst,
symlink=False,
ignore=None,
copy_function=copy2,
ignore_dangling_symlins=False)
Here,
- src - source directory from where the files shall be copied.
- dst - destination to where the files shall be copied.
-
If symlinks are True,
- Move the file with new name
- Copy and rename file using "os" module
Move and Rename file
shutil.move(src, dst, copy_function=copy2)
Listing command:
-bash-4.2$ ls
python_samples test test.txt test.txt.copy test.txt.copy2
Code:
# importing modules
import os
import shutil
src_dir = os.getcwd()
# gets the current working dir
dest_file = src_dir + "/python_samples/test_renamed_file.txt"
shutil.move('test.txt',dest_dir)
print(os.listdir())
# the file 'test.txt' is moved from
# src to dest with a new name
os.chdir(dest_dir)
print(os.listdir()) # list of files in dest
Output
'/home/sradhakr/Desktop/my_work/python_samples/ test_renamed_file.txt’
['python_samples', 'test', 'test.txt.copy', 'test.txt.copy2']
['.git', '.gitignore', 'README.md', 'src', ' test_renamed_file.txt']
Copy and rename using os and shutil module
In this approach we use the shutil.copy() function to copy the file and os.rename() to rename the file.
# Importing the modules
import os
import shutil
src_dir = os.getcwd() #get the current working dir
print(src_dir)
# create a dir where we want to copy and rename
dest_dir = os.mkdir('subfolder')
os.listdir()
dest_dir = src_dir+"/subfolder"
src_file = os.path.join(src_dir, 'test.txt.copy2')
shutil.copy(src_file,dest_dir) #copy the file to destination dir
dst_file = os.path.join(dest_dir,'test.txt.copy2')
new_dst_file_name = os.path.join(dest_dir, 'test.txt.copy3')
os.rename(dst_file, new_dst_file_name)#rename
os.chdir(dest_dir)
print(os.listdir())
Output
/home/user/Desktop/my_work
['python_samples', 'subfolder', 'test', 'test.txt.copy2', 'test.txt.copy_1']
'/home/sradhakr/Desktop/my_work/subfolder/test.txt.copy2'
['test.txt.copy3']
Summary: shutil (shell utilities module ) is a more pythonic way to perform the file or directory copy , move or rename operations.
Reference: https://docs.python.org/3/faq/windows.html