首页 > 解决方案 > copying images to certain folder

问题描述

I am new to python I am trying to build a small script that can collect images from all over the server, I have certain image naming:

AMZ_1004.jpg
AMZ_1272.jpg
GOO_1.jpeg
GOO_2.png

I want the script to look through every directory and copy (not move) the files into AMZ & GOO

import shutil,os

goo_dst = '/home/usr2/Pictures/GOO'
amz_dst = '/home/usr2/Pictures/AMZ'
os.makedirs(goo_dst,exist_ok=1)
os.makedirs(amz_dst,exist_ok=1)
for root, dirs, files in os.walk('/'):
    for name in files:
        path = os.path.join(root, name)
        if name.startswith('GOO_') and (name.endswith('.jpg') or name.endswith('.jpeg') or name.endswith('.png')):
            shutil.copyfile(path, goo_dst)
        elif name.startswith('AMZ_') and name.endswith('.jpg'):
            shutil.copyfile(path, amz_dst)

the script runs ok, is there a way speed the process ?

the script runs on Arch Linux if it matters

标签: pythonpython-2.7python-2.x

解决方案


您可以对脚本进行的最大优化不是在文件系统根目录上开始搜索。

这种方法会检查许多不是文件的东西(例如/dev/proc文件夹)以及文件不太可能存在的系统文件夹。(您真的不希望任何图像低于/bin/usr/bin正确?)

尝试缩小真正的搜索路径,例如/var/wwwApache 文件夹所在的位置。

另一个优化可能根本不使用 Python,而是直接使用 shell 脚本:

#!/bin/sh
GOO_DST='/home/usr2/Pictures/GOO'
AMZ_DST='/home/usr2/Pictures/AMZ'

mkdir -p ${GOO_DST}
mkdir -p ${AMZ_DST}

find / -type f -name 'GOO_*.jpg' -o -name 'GOO_*.jpeg' -o -name 'GOO_*.png' -exec cp {} ${GOO_DST} \;

find / -type f -name 'AMZ_*.jpg' -exec cp {} ${AMZ_DST} \;

find实用程序应该为您提供比手动遍历更快的结果。

如果您坚持使用 Python,至少移动path = os.path.join(root, name)以避免对不相关的文件(大多数文件)进行一些额外的工作。这是一个很小的优化,但仍然可以提供帮助。

另一种选择是使用多线程来并行化搜索,但您需要手动决定每个线程将搜索文件系统的哪个部分。

如果 2 个线程遍历相同的文件夹,那将是更大的时间浪费。另外,请注意,多线程处理此脚本可能会导致它在运行时占用更多 CPU。

阅读此处了解更多详情


推荐阅读