玩蛇网提供最新Python编程技术信息以及Python资源下载!

菜鸟的递归查找文件python实现

python 培训

做为一个python学习的菜鸟,老师说不停的写代码是最好的学习方式。这次我写的是递归查找文件python实现:具体实现方法如下
1、首先,输入要查找的特定目标文件扩展名,来遍历查找特定扩展名的文件。这里是:eg:python find_file.py txt;
2.之后通过-f来指定将结果写入到特定名称的文件:eg:python -f txt_result txt,否则将结果打印在控制台;
3最后,要在指定要查找的特定扩展名文件后,找到指定查找的根目录:eg:python find_file.py txt /;

python菜鸟新手写的代码,如果有不妥之处,还请高手指正。

菜鸟的递归查找文件python实现

#!/usr/bin/python
#-*-coding:utf8-*-

import sys
import os
import argparse
import pdb
from pprint import pprint

def find_path_file(specific_file,search_directory):
    """
    result_path_filename
    """
    result_path_filename = list()
    result_path_filename.extend([os.path.join(dirpath,filename) for dirpath,dirnames,filenames in os.walk(search_directory) for filename in filenames if os.path.splitext(filename)[1] == ('.' + specific_file)])
    pprint(result_path_filename)

def find_file(specific_file,search_directory):
    """
    result_filename don't have path
    """
    result_filename = list()
    os.path.walk(search_directory,lambda arg,dirname,names:result_filename.extend([i for i in names if os.path.splitext(i)[1] == ('.' + specific_file)]),())
    pprint(result_filename)

def save_result_to_file(_filename,specific_file,search_directory):
    """
    save result to specific file
    """
    result_path_filename = list()
    result_path_filename.extend([os.path.join(dirpath,filename) for dirpath,dirnames,filenames in os.walk(search_directory) for filename in filenames if os.path.splitext(filename)[1] == ('.' + specific_file)])
    with open(_filename,'w') as f:
        f.write("\n".join(result_path_filename))

#www.iplaypython.com

if __name__ == "__main__":
    par
4534
ser = argparse.ArgumentParser()
    parser.add_argument("file_suffix",help="specific the file suffix")
    parser.add_argument("rootdir",help="specific the root directory")
    parser.add_argument("-f","--file",help="record result to file")
    args = parser.parse_args()
    specific_file = args.file_suffix
    search_directory = args.rootdir
    if args.file:
        filename = args.file
        save_result_to_file(filename,specific_file,search_directory)
    else:
#        find_file(specific_file,search_directory)
        find_path_file(specific_file,search_directory)

python递归其它相关文章推荐:
1、Python无限递归的概念教程
2、Python指定目录递归遍历源码

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/text-file/tf2239.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-06-07 10:24 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部