Reputation: 20302
I am testing an idea to copy all files with the extension '.yaml' from one folder (and all sub-folders) to another folder. I came up with the code below.
import os
import shutil
src = 'C:\\Users\\ryans\\OneDrive\\Documents\\GitHub\\Pipeline\\'
dest = 'C:\\Users\\ryans\\OneDrive\\Desktop\\AllYAML\\'
#src_files = os.listdir(src)
for root, dirs, files in os.walk(src):
for filename in files:
full_file_name = os.path.join(src, filename)
if (os.path.isfile(full_file_name)):
if full_file_name.endswith('.yaml'):
shutil.copy(full_file_name, dest)
This seems right, for the most part, but it is only copying over two files with the extension '.yaml' from source to destination. There are around 130 files in all folders and sub-folders, so I know something is off here, but I don't know quite what the issue is.
Upvotes: 2
Views: 844
Reputation: 76
this should copy all the .yaml files from src folder and its sub-folders into dest folder, keeping in mind the src sub-folder structure will NOT BE maintained in dest.
import os
import shutil
src = 'C:\\Users\\ryans\\OneDrive\\Documents\\GitHub\\Pipeline\\'
dest = 'C:\\Users\\ryans\\OneDrive\\Desktop\\AllYAML\\'
#src_files = os.listdir(src)
for root, dirs, files in os.walk(src):
for filename in files:
full_file_name = os.path.join(root, filename)
if (os.path.isfile(full_file_name)):
if full_file_name.endswith('.yaml'):
shutil.copy(full_file_name, dest)
Mainly filename is to be joined with respective directory to which it belongs like full_file_name = os.path.join(root, filename)
Upvotes: 1
Reputation: 106455
You should join the path of the file with the file name instead of joining the starting path with the file name.
Change:
full_file_name = os.path.join(src, filename)
to:
full_file_name = os.path.join(root, filename)
Upvotes: 1