简体   繁体   English

如何使用 python 根据源文件夹将所有 csv 文件从不同的源文件夹复制到目标?

[英]how to copy all csv files from different source folders into target as per source folders using python?

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.我有如下代码从不同的源文件夹复制所有 *.csv 文件,但我想根据源复制到不同的文件夹中,我可以将所有 csv 文件复制到单个文件夹,但我希望它作为源文件夹进入不同的文件夹.

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:您可以使用os.path.relpath为通用方法提取子路径,并os.makedirs在目标上创建缺少的目录:

    ...
    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM