python搜索指定类型文件&批量移动文件程序

搜索文件并移动的python程序

使用python写一个程序,其功能满足:可以搜索指定目录下的某类型的文件,并可以移动到指定的目录。

                   《python搜索指定类型文件&批量移动文件程序》

文章目录

ʚʕ̯•͡˔•̯᷅ʔɞ 个人简介
欢迎各路大佬来到小啾主页指点
博客主页:云雀编程小窝 ꧔ꦿ
꧔ꦿ点赞 + 关注 + 收藏
                    《python搜索指定类型文件&批量移动文件程序》
感谢大家的支持:一起加油!共同进步!
《python搜索指定类型文件&批量移动文件程序》

1.示例文件及路径准备

作为示例,在D盘中放一个名为pic1的文件夹,在该文件夹中放入两个png图片,并在pic1内再创建一个文件夹,里边也随便放两张png图片。如图所示。

在D盘的ABC文件夹中,创建一个名为pic2的文件夹。

本程序要求:搜索目录”D://pic1″下的所有文件扩展名为png的图片。并将其全部移动至”D://ABC/pic2″目录下。

《python搜索指定类型文件&批量移动文件程序》

《python搜索指定类型文件&批量移动文件程序》

2.代码示例

分别定义一个搜索函数和一个批量移动函数。
搜索函数需要传入的参数为root:要搜索的目录;target为目标文件类型(即扩展名)。
搜索函数输出 由目标文件path+文件名构成的列表。

批量移动函数传入的file_list参数是一个列表,形如搜索函数的输出结果,元素为带有path的文件名。dest为需要移动到的目录。

import os, shutil

file_list = []

# 搜索函数
def search_file(root, target):
    for file in os.listdir(root):
        path = root
        try:
            path = path + os.sep + file
            if os.path.isdir(path):
                search_file(path, target)
            else:
                if file.split('.')[-1] == target:
                    file_list.append(path)
        except PermissionError as e:
            print(e)
    return file_list


# 批量移动函数
def move_file(file_list, dest):
    for file in file_list:
        try:
            shutil.move(file, dest)
        except shutil.Error as e:
            print(e)


# 写入目标参数root,
def main():
    root = "D:\\pic1"
    target = "png"
    dest_dir = "D:\\ABC\\pic2"
    result = search_file(root, target)
    print(result)
    move_file(result, dest_dir)


if __name__ == '__main__':
    main()

《python搜索指定类型文件&批量移动文件程序》

如图,目标文件被成功搜索出并转移:
《python搜索指定类型文件&批量移动文件程序》

  • 其中搜索函数需要用到递归的写法,对文件夹中的不定数的文件夹进行遍历。
  • 且在其中使用到了异常处理的写法,是为了避免遇到不可访问的系统文件夹,导致程序运行中断。(除C盘外,这样的文件夹通常不会在二级中,比如在D盘的根目录下可能会有。这里的异常处理写法可以有效解决该问题。)

3.命令行写法

将上述代码改写文能在命令行传参、调用的形式。

首先将目标文件放回原路径,放好。

import sys
import os, shutil


file_list = []


# 定义一个搜索功能的函数
def search_file(root, file_name):
    for file in os.listdir(root):
        path = root
        try:
            path = path + os.sep + file
            if os.path.isdir(path):
                search_file(path, file_name)
            else:
                if file.split('.')[-1] == file_name:
                    file_list.append(path)
        except PermissionError:
            pass
    return file_list


def move_file(file_list, dest):
    for file in file_list:
        shutil.move(file, dest)


def main(argv):
    root = argv[1]
    target = argv[2]
    dest_dir = argv[3]
    result = search_file(root, target)
    print(result)
    move_file(result, dest_dir)


if __name__ == '__main__':
    main(sys.argv)

打开cmd,目录调整好后,输入py文件名(这里为demo.py)及依次传入三个参数。
即执行命令:
《python搜索指定类型文件&批量移动文件程序》
代码成功运行,目标文件位置被更改。
《python搜索指定类型文件&批量移动文件程序》

    原文作者:侯小啾
    原文地址: https://blog.csdn.net/weixin_48964486/article/details/123221467
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞