You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将源文件夹内所有PNG图片及zip文件批量拷贝到目标文件夹

实现逻辑

  • 首先新增目标目录自动创建逻辑,避免路径不存在时拷贝报错
  • 匹配规则新增*.png和*.zip两种后缀的文件,可按需兼容大小写场景
  • 遍历所有匹配到的文件执行拷贝操作即可

完整可运行代码

兼容大小写后缀版本(适用Windows等大小写不敏感系统)

import glob
import shutil
import os

src_dir = "your/source/dir"
dst_dir = "your/destination/dir"

# 自动创建目标目录,已存在时不报错
os.makedirs(dst_dir, exist_ok=True)

# 匹配png、zip所有大小写组合的后缀
png_files = glob.iglob(os.path.join(src_dir, "*.[pP][nN][gG]"))
zip_files = glob.iglob(os.path.join(src_dir, "*.[zZ][iI][pP]"))

for file in list(png_files) + list(zip_files):
    shutil.copy(file, dst_dir)

仅匹配小写后缀版本(更简洁,适用Linux/macOS等大小写敏感系统)

import glob
import shutil
import os

src_dir = "your/source/dir"
dst_dir = "your/destination/dir"

os.makedirs(dst_dir, exist_ok=True)

# 遍历两种后缀的文件
for suffix in ["*.png", "*.zip"]:
    for file in glob.iglob(os.path.join(src_dir, suffix)):
        shutil.copy(file, dst_dir)

注意事项

  • 如果需要保留原jpg文件的拷贝逻辑,直接在后缀列表里添加*.jpg/*.[jJ][pP][gG]即可
  • 如果需要递归匹配源目录子文件夹里的对应文件,可以给glob.iglob加recursive=True参数,同时路径通配符改成**/*.png的格式

内容的提问来源于stack exchange,提问作者Engr Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:24:03