python - 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
解决方案
您可以对脚本进行的最大优化不是在文件系统根目录上开始搜索。
这种方法会检查许多不是文件的东西(例如/dev
和/proc
文件夹)以及文件不太可能存在的系统文件夹。(您真的不希望任何图像低于/bin
或/usr/bin
正确?)
尝试缩小真正的搜索路径,例如/var/www
Apache 文件夹所在的位置。
另一个优化可能根本不使用 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。
推荐阅读
- google-admin-sdk - Google Directory API 用户创建,然后发送欢迎电子邮件
- java - 如何在不使用数组或任何正则表达式的情况下缩进包含特殊关键字的文本文件中的文本
- javascript - 如何做到这一点,当您按下 png 图标时,它会将您带到 NavLink 中“/”的主页,而无需重新加载页面?
- javascript - 悬停时更改底部边框的颜色
- angular5 - 纱线链接,对链接包的更改未反映在主机应用程序中
- javascript - 将主要 Typescript 代码及其依赖项组合在一个文件中
- activiti - 如何在不取消用户任务的情况下通过信号边界事件启动子进程
- python - Python:带有自定义标头的请求失败
- java - 扩展类的构造函数被调用两次
- javascript - 角度路由不显示模板