首页 > 解决方案 > 如何在多个子目录中找到具有相同扩展名的所有文件并使用 python 将它们移动到单独的文件夹中?

问题描述

我已将旧摄像机的内容复制到我的计算机上,在转移到那里的文件夹中,有 100 多个子文件夹,所有这些子文件夹都包含我想要的 6 或 7 个文件。如何能够搜索所有这些并将所有找到的文件移动到新文件夹?我对此很陌生,所以欢迎任何帮助。

标签: pythonfile-management

解决方案


要找到所有文件,有两种方法:

  1. 使用 os.walker

例子:

import os

path = 'c:\\location_to_root_folder\\'

files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.mpg' in file:
            files.append(os.path.join(r, file))

for f in files:
    print(f)
  1. 使用 glob 示例:
import glob

path = 'c:\\location_to_root_folder\\'

files = [f for f in glob.glob(path + "**/*.mpg", recursive=True)]

for f in files:
    print(f)

要移动,您可以使用以下 3 种方法中的任何一种,我个人更喜欢 shutil.move:

import os
import shutil

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

推荐阅读