I have code as below to copy all *.csv files from different source folders, but i want to copy in different folders as per source, i could able to copy all csv files to single folder but i want it into different folders as source folders.
import os
import shutil
import fnmatch
dir = 'C:\\data\\projects\\'
patterns = ['project1','project2']
dest = 'D:\\data\\projects\\'
for root, dirs, files in os.walk(dir):
for pattern in patterns:
for filename in fnmatch.filter(files, '*.csv'):
source = (os.path.join(root, filename))
print(source)
shutil.copy(source, dest)
You could use os.path.relpath
to extract the subpath for a general method, and os.makedirs
to create missing directories on the destination:
...
for filename in fnmatch.filter(files, '*.csv'):
source = (os.path.join(root, filename))
print(source)
rel = os.path.relpath(root, dir)
curdest = os.path.join(dest, rel)
if not os.path.exists(curdest):
os.makedirs(curdest, exist_ok=True)
shutil.copy(source, curdest)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.