【问题标题】:Copy nth files before every matching file in Python在 Python 中的每个匹配文件之前复制第 n 个文件
【发布时间】:2021-10-01 17:37:45
【问题描述】:

我正在尝试解决准备数据集的耗时任务。这里我展示一个简化版本。首先,我比较两个文件夹以找到匹配的文件(图像文件名)。

文件夹 1:随机文件(3 个文件)。 文件夹 2:连续 1 分钟的图像(36 个文件)。

https://drive.google.com/drive/folders/1A0KueRjkBhYxdF0LfLk6YWFkg_jVAiDw?usp=sharing

我想将位于文件夹 2 中每个匹配文件之前的 5 个文件(图像)复制到一个新文件夹中。我被困在为每个匹配文件查找这些相邻(先前)文件。我没有得到每个匹配文件的文件。有 3 场比赛。我只得到最后 5 个文件。

import os 
import shutil
import filecmp

comparison = filecmp.dircmp('folder1', 'folder2').common
files = os.listdir('folder2')

for i in range (len(files)):
    if comparison:
        new = files[max(0, i - 5):]

for i in new:        
     os.chdir('path')
     shutil.copy(i, path)

【问题讨论】:

    标签: python loops file match shutil


    【解决方案1】:

    我不完全确定您要达到的目标,但我认为这可行:

    ...
    
    new = []
    for i, file in enumerate(files):
        if file in comparison:
            new.extend(files[max(0, i-5):i])
    ...
    

    如果不扩展new,你会为每场比赛覆盖它,即只有最后一场比赛可用。你的if comparison: 行很奇怪:它总是评估为True,因为列表comparison 不是空的(这里)。我的猜测是,您只希望匹配 comparison 中的文件 - 这就是我替换它的方式。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2019-03-17
      相关资源
      最近更新 更多