- 1 year ago
I need to copy all the files and it's folder to the target destination using globbing pattern
Comment
1 / 1
To copy all files and their folders to a target destination using globbing patterns in Python, you can utilize the glob
module along with the shutil
module. Here's an example:
pythonimport glob
import shutil
import os
source_folder = "/path/to/source/folder"
target_folder = "/path/to/target/folder"
# Get a list of all files and folders in the source folder using a globbing pattern
files = glob.glob(os.path.join(source_folder, "**"), recursive=True)
# Iterate through the files and folders
for item in files:
# Create the corresponding destination path by replacing the source folder with the target folder
destination = os.path.join(target_folder, os.path.relpath(item, source_folder))
if os.path.isfile(item):
# If it's a file, copy it to the destination
shutil.copy2(item, destination)
elif os.path.isdir(item):
# If it's a directory, create the corresponding directory in the destination
os.makedirs(destination, exist_ok=True)
In this example:
- Set the
source_folder
variable to the path of the source folder containing the files you want to copy. - Set the
target_folder
variable to the path of the destination folder where you want to copy the files. - Use
glob.glob()
with therecursive=True
argument to retrieve a list of all files and folders in the source folder, including subdirectories, using a globbing pattern (**
matches any number of subdirectories). - Iterate through each file and folder in the list.
- For each item, create the corresponding destination path by replacing the source folder with the target folder using
os.path.relpath()
. - If the item is a file, copy it to the destination using
shutil.copy2()
. - If the item is a directory, create the corresponding directory in the destination using
os.makedirs()
.
By running this Python script, all files and their folders from the source folder will be copied to the target destination while preserving the folder structure.