Python脚本:查找指定类型文件

Jul 7,2017   1047 words   4 min

Tags: Python

一、代码

# Python 2.7
# coding=utf-8
import os.path

root_dir = raw_input("Input the folder you are going to search(e.g. E:\\videos):\n") + "\\"

out_dir = raw_input("Input the folder to save search result(e.g. F:\\files):\n") + "\\"

f_type = raw_input("Input type of files(e.g. mp4):\n")

paths = []

print 'searching...'

count = 0

# 遍历
for parent, dirname, filenames in os.walk(root_dir):
    for filename in filenames:
        if filename.endswith(f_type):

            # 如果父路径不是以\结束,添加上
            if parent[-1] != '\\':
                parent += '\\'

            # 如果父路径中有\\,则替换成\
            if parent.__contains__("\\\\"):
                parent = parent.replace("\\\\", "\\")

            temp = parent + filename
            paths.append(temp)

        count += 1
        print 'searched', count, 'files...'

print 'Search result:'

if paths.__len__() is not 0:
    for path in paths:
        print path

print paths.__len__(), f_type, "files were found."

if paths.__len__() is not 0:
    if out_dir.__contains__("\\\\"):
        parent = parent.replace("\\\\", "\\")

    print 'Results were saved to', out_dir + "search result.txt"

    output = open(out_dir + "search result.txt", 'w')

    for item in paths:
        output.write(item + "\n")

    output.close()

二、测试

例如,查找某个文件夹下的tif文件,输入如下内容。 搜索结果: 输出结果: 编写完代码后才忽然想起来,Windows自带搜索功能就可以进行文件类型的搜索,而且速度很快。 所以这代码全当练习吧,可能没有太大实际价值。

本文作者原创,未经许可不得转载,谢谢配合

返回顶部