Can someone help me about how to copy all files from a folder to another destination folder in python. The catch is I do not want to copy the sub-directory structure. But I want the files within them.
For example, lets say in the root folder, there are 3 folders, each containing 10 files. Also in each of them there are 2 folders each containing 5 files. (so each first level folder has in total 20 files and 2 sub directories under it). Bringing the total to 60 files.
I wish to copy all of those 60 files to a single destination directory, discarding the subfolder structure.
This is the code I've tried:
# path : source folder path
# compiled_path: destination folder path
w = os.walk(path)
for root, dirs, files in w:
for dir_name in dirs:
file_list_curent_dir = os.walk(path+"\\"+dir_name).next()[2]
for item in file_list_curent_dir:
shutil.copy(path+"\\"+dir_name+"\\"+item, compiled_path+"\\"+item )
It copies the files uppermost level, not the folders within sub-directories.
Thank you very much for your time.
Type "xcopy", "source", "destination" /t /e in the Command Prompt window. Instead of “ source ,” type the path of the folder hierarchy you want to copy. Instead of “ destination ,” enter the path where you want to store the copied folder structure. Press “Enter” on your keyboard.
move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory.
Copying Directories with cp Command To copy a directory, including all its files and subdirectories, use the -R or -r option. The command above creates the destination directory and recursively copy all files and subdirectories from the source to the destination directory.
Once the files are visible, press Ctrl-A to select all of them, then drag and drop them to the right location. (If you want to copy the files to another folder on the same drive, remember to hold down Ctrl while you drag and drop; see The many ways to copy, move, or delete multiple files for details.)
import os
import shutil
for root, dirs, files in os.walk('.'): # replace the . with your starting directory
for file in files:
path_file = os.path.join(root,file)
shutil.copy2(path_file,'destination_directory') # change you destination dir
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With