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

如何将目录及子目录中的文件移动到指定目录(含重名文件处理)

问题:递归移动子目录中同名图片到单一目录

我有大量存储在多个子目录中的图片需要移动到一个单独的目录中,其中许多文件即使位于不同子目录也完全同名。我尝试了以下代码,它能正常运行,但无法访问子目录中的文件,请问需要做哪些修改才能同时移动子目录中的文件?

import os
import shutil
import datetime
import glob

now = str(datetime.datetime.now())
now = now.replace(":","")
count = 1

dirr = 'path'
move = '/path_to_directory_where_the_files_are_to_be_moved'
for files in os.listdir(dirr): 
    if files.endswith('20.jpg') or files.endswith('29.jpg'):
        src = dirr + files
        dst = move + files+str(now)+'.jpg'
        shutil.copy(src, dst)
        print("copied " + str(count) +' files \n')
        count +=1

问题分析

原代码的核心局限是os.listdir(dirr)仅能遍历目标目录的当前层级,无法递归进入子目录读取文件,因此子目录中的图片不会被处理。

解决后的代码

import os
import shutil
import datetime
import glob
import time
count = 1

dirr = 'path'
move = '/path_to_directory_where_the_files_are_to_be_moved'

for files in glob.glob(dirr + '/**', recursive=True):
    if files.endswith('20.jpg') or files.endswith('29.jpg'):
        now = str(datetime.datetime.now())
        now = now.replace(":","")
        print(files)
        files1 = os.path.basename(files)
        dst = move + files1+str(now)+'.jpg'
        #print(src, dst)
        shutil.copy(files, dst)
        #time.sleep(0.05) ## 仅在需要确保每个文件绝对唯一命名时使用,通常不需要
        print("copied " + str(count) +' files \n')
        count +=1

关键修改说明

  • 递归遍历子目录:使用glob.glob(dirr + '/**', recursive=True),其中**匹配任意层级的子目录,recursive=True开启递归模式,能获取所有子目录下的完整文件路径。
  • 唯一文件名处理:将时间戳生成逻辑移至循环内部,确保每个文件复制时生成独立的时间戳,避免同名文件覆盖;若需更稳妥,可取消time.sleep(0.05)的注释,增加微小延迟保证时间戳唯一性。
  • 修正源路径:直接使用glob返回的files作为源文件路径,原代码中src = dirr + files1会丢失子目录路径,导致无法找到文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:06:09