将文件夹目录中的所有.csv文件复制到python中的一个文件夹 [英] Copy all .csv files in a directory of folders to one folder in python

查看:538
本文介绍了将文件夹目录中的所有.csv文件复制到python中的一个文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将父文件夹中的所有.csv文件及其中的所有子文件夹复制到新的目标位置( C:/ Projects / CSVFiles)。

I am trying to copy all .csv files within a parent folder and all sub-folders within, to a new destination ("C:/Projects/CSVFiles").

我使用了以下代码(从论坛上的其他地方),但这仅复制父目录(DataFiles)中的.csv文件,而不是/ datafiles /中的子文件夹。

I have used the following code(from elsewhere on the forum) but this only copies the .csv files in the parent directory (DataFiles) and not from the sub-folders within /datafiles/.

任何建议都值得赞赏。谢谢

Any advice appreciated. Thanks

import glob
import shutil
import os

src_dir = "C:/Projects/DataFiles"
dst_dir = "C:/Projects/CSVFiles"
for CSVfile in glob.iglob(os.path.join(src_dir, "*.csv")):
shutil.copy(Excelfile, dst_dir)


推荐答案

使用 os.walk 遍历目录树。

import os
import shutil
src_dir = "C:/Projects/DataFiles"
dst_dir = "C:/Projects/CSVFiles"
for root, dirs, files in os.walk(src_dir):
    for f in files:
        if f.endswith('.csv'):
            shutil.copy(os.path.join(root,f), dst_dir)

这篇关于将文件夹目录中的所有.csv文件复制到python中的一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆