【问题标题】:Copy specific files from directory and subdirectories into new directory Python将目录和子目录中的特定文件复制到新目录 Python
【发布时间】:2019-11-01 03:53:12
【问题描述】:

我是 Python 的初学者。我想将特定文件(使用模式匹配和shutil.copy)从目录和子目录(使用os.walk)复制到一个新目录中。 该代码仅适用于一个子目录中的一个文件,但不适用于多个子目录。

通过使用模式匹配和shutil.copy,可以将仅一个子目录中的一个特定文件复制到一个新目录中。 当我想匹配来自不同子目录的特定文件时,无法复制到新目录中。

这里是一个子目录中文件的代码:

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)

我在考虑使用递归副本,或 shutil.copytree,但我不太确定。

谢谢

【问题讨论】:

    标签: python copy pattern-matching subdirectory shutil


    【解决方案1】:

    我猜你是在 Windows 上?

    您可以使用 subprocess 或 os.system 以编程方式调用“dir”命令并使用输出。您可以使用的标志是

    dir /s /b
    

    /s 用于子目录和 /b 用于裸输出

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 2011-10-14
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      相关资源
      最近更新 更多