【问题标题】:Trying to pass files from a subfolder to a new folder after Filtering过滤后尝试将文件从子文件夹传递到新文件夹
【发布时间】:2021-09-29 13:10:57
【问题描述】:

我正在尝试编写允许我将文件从各种子文件夹复制到新文件夹的代码。主要问题以及为什么从一开始就不是一件直截了当的事情是所有文件的开头和结尾都相同,我需要的文件中只有 1 个字母的变化。

我不断收到一条错误消息:“FileNotFoundError: [Errno 2] No such file or directory: '20210715 10.1_Plate_R_p00_0_B04f00d0.TIF'”

到目前为止,这是我所拥有的:

import os,fnmatch, shutil
mainFolder = r"E:\Screening\202010715\20210715 Screening"
dst = r"C:\Users\**\Dropbox (**)\My PC\Desktop\Screening Data\20210715"

for subFolder in os.listdir(mainFolder):
    sf = mainFolder+"/"+subFolder
    id os.path.isdir(sf):
        subset = fnmatch.filter(os.listdir(sf), "*_R_*")  
        
for files in subset:
    if '_R_' in files:
        shutil.copy(files, dst)

请帮忙!

【问题讨论】:

  • 我刚刚看到一个错误,是复制粘贴错误 --> if os.path.isdir(sf): noot ----id os.path.isdir(sf):

标签: python shutil fnmatch


【解决方案1】:

问题是您没有将文件的完整路径提供给shutil.copy,因此它假定该文件存在于您运行脚本的文件夹中。代码的另一个问题是,subset 变量在每个循环中被替换,然后您才能复制在下一个循环中匹配的文件。

import os, fnmatch, shutil
mainFolder = r"E:\Screening\202010715\20210715 Screening"
dst = r"C:\Users\**\Dropbox (**)\My PC\Desktop\Screening Data\20210715"
matches = [] # To store the matches

for subFolder in os.listdir(mainFolder):
    sf = mainFolder + "/" + subFolder
    if os.path.isdir(sf):
        matches.extend([f'{sf}/{file}' for file in fnmatch.filter(os.listdir(sf), "*_R_*")]) # Append the full path to the file
            
        
for files in matches:
    shutil.copy(files, dst)    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 2018-12-20
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2018-06-14
    相关资源
    最近更新 更多