简体   繁体   English

将目录和子目录中的特定文件复制到新目录Python中

[英]Copy specific files from directory and subdirectories into new directory Python

I am a beginner on Python. 我是Python的初学者。 I would like to copy specific files (using pattern matching and shutil.copy) from directory and sub directories (using os.walk) into a new directory. 我想将目录和子目录(使用os.walk)中的特定文件(使用模式匹配和shutil.copy)复制到新目录中。 The code works only for one file from one sub directory but not with multiple sub directories. 该代码仅适用于一个子目录中的一个文件,但不适用于多个子目录。

One specific file in only one sub directory can be copied into a new directory by using pattern matching and shutil.copy. 通过使用模式匹配和shutil.copy,只能将一个子目录中的一个特定文件复制到新目录中。 When I want to match specific files from different sub directories it's not possible to copy into the new directory. 当我想匹配来自不同子目录的特定文件时,无法复制到新目录中。

Here the code for the file in one sub directory : 这里是一个子目录中文件的代码:

import os
import shutil
import shutil
from fnmatch import fnmatch

root = r'C:\Users\Fabien.Seychelles\Documents\Projects\Python_weather\Weather_Files'
dest =r'C:\Users\Fabien.Seychelles\Documents\Projects\Python_weather\CSV_converted'

pattern2 = '*TMY*.epw' 

for path, subdirs, files in os.walk(root):
    for filename in files:
        if fnmatch(filename, pattern2):
            shutil.copy(root + '\\'+ filename, dest)

I was thinking about using a recursive copy, or shutil.copytree but I am not really sure. 我正在考虑使用递归副本或shutil.copytree,但我不太确定。

Thank you 谢谢

I'm guessing you're on windows? 我猜你在窗户上?

You could call the "dir" command programmatically using subprocess or os.system and consume the output. 您可以使用subprocess或os.system以编程方式调用“dir”命令并使用输出。 The flags you could use are 你可以使用的标志是

dir /s /b

/s for sub-directories and /b for bare output / s表示子目录,/ b表示裸输出

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

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