python - 在python中定位大数据集中的多个文件

标签 python python-3.x os.walk

我有一个大型图像文件存储库(约 200 万,.jpg),各个 id 分布在多个子目录中,我试图在包含以下内容的列表中找到并复制每个图像:这些 id 的大约 1,000 个子集。

我对 Python 还很陌生,所以我的第一个想法是使用 os.walk 迭代每个文件的 1k 子集,看看子集中是否有任何与 id 匹配的文件。至少在理论上,这是可行的,但对于每秒 3-5 张图像来说,速度似乎非常慢。运行一次查找一个 id 的所有文件似乎也是同样的情况。

import shutil
import os
import csv

# Wander to Folder, Identify Files
for root, dirs, files in os.walk(ImgFolder):
    for file in files:
        fileName = ImgFolder + str(file)
# For each file, check dictionary for match
        with open(DictFolder, 'r') as data1:
            csv_dict_reader = csv.DictReader(data1)
            for row in csv.DictReader(data1):
                img_id_line = row['id_line']
                isIdentified = (img_id_line in fileName) and ('.jpg' in fileName)
# If id_line == file ID, copy file
                if isIdentified:
                    src = fileName + '.jpg'
                    dst = dstFolder + '.jpg'
                    shutil.copyfile(src,dst)
                else:
                    continue

我一直在考虑尝试自动执行查询搜索,但数据包含在 NAS 上,而且我没有简单的方法来对文件建立索引以加快查询速度。我运行代码的机器是 W10,因此我无法使用 Ubuntu Find 方法,我认为该方法在这项任务上要好得多。

任何加快该过程的方法将不胜感激!

最佳答案

这里有几个脚本应该可以满足您的需求。

index.py

此脚本使用 pathlib遍历目录搜索具有给定扩展名的文件。它将写入一个包含两列的 TSV 文件:文件名和文件路径。

import argparse
from pathlib import Path


def main(args):
    for arg, val in vars(args).items():
        print(f"{arg} = {val}")

    ext = "*." + args.ext
    index = {}
    with open(args.output, "w") as fh:
        for file in Path(args.input).rglob(ext):
            index[file.name] = file.resolve()
            fh.write(f"{file.name}\t{file.resolve()}\n")


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument(
        "input",
        help="Top level folder which will be recursively "
        " searched for files ending with the value "
        "provided to `--ext`",
    )
    p.add_argument("output", help="Output file name for the index tsv file")
    p.add_argument(
        "--ext",
        default="jpg",
        help="Extension to search for. Don't include `*` or `.`",
    )
    main(p.parse_args())

search.py​​

此脚本会将索引(index.py 的输出)加载到字典中,然后将 CSV 文件加载到字典中,然后对于每个 id_line 它将在索引中查找文件名并尝试将其复制到输出文件夹。

import argparse
import csv
import shutil
from collections import defaultdict
from pathlib import Path


def main(args):
    for arg, val in vars(args).items():
        print(f"{arg} = {val}")

    if not Path(args.dest).is_dir():
        Path(args.dest).mkdir(parents=True)

    with open(args.index) as fh:
        index = dict(l.strip().split("\t", 1) for l in fh)
    print(f"Loaded {len(index):,} records")

    csv_dict = defaultdict(list)

    with open(args.csv) as fh:
        reader = csv.DictReader(fh)
        for row in reader:
            for (k, v) in row.items():
                csv_dict[k].append(v)

    print(f"Searching for {len(csv_dict['id_line']):,} files")
    copied = 0
    for file in csv_dict["id_line"]:
        if file in index:
            shutil.copy2(index[file], args.dest)
            copied += 1
        else:
            print(f"!! File {file!r} not found in index")
    print(f"Copied {copied} files to {args.dest}")


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("index", help="Index file from `index.py`")
    p.add_argument("csv", help="CSV file with target filenames")
    p.add_argument("dest", help="Target folder to copy files to")
    main(p.parse_args())

如何运行它:

python index.py --ext "jpg" "C:\path\to\image\folder" "index.tsv"
python search.py "index.tsv" "targets.csv" "C:\path\to\output\folder"

我会首先在一个/两个文件夹上尝试此操作,以检查它是否具有预期结果。

关于python - 在python中定位大数据集中的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68728414/

相关文章:

python - Python 中的返回值

python - 如何在 travis 上使用 osx 环境构建 python 项目

python - Tkinter : Issue with creating keyboard shortcuts

python - 在Python3中使用Script = argv

python - 如何返回最大深度的子目录路径?

python - 过滤 os.walk() 目录和文件

python - DFS 的 Cython 并行化竞争条件

python-3.x - RPi.GPIO 引脚 - 检查状态

python - 类型错误 : 'pygame.Surface' object is not callable [Pygame module]

python - os.walk onerror 的函数返回到哪里?如何向 onerror 函数调用添加更多参数?