Python递归获取给定目录下的所有文件的文件名

实现代码:

import os


def get_filename(path, allfile, dict_filetype=None):
    '''递归获得所有符合条件的文件名 
    
    @param : path 起始目录,要检查的根目录 
    @param : allfile 传入的初始文件名列表,填空即可
    @param : dict_filetype 要检查的文件类型,为None时则不检查返回所有。默认为None
    @return: 列表 所有与 dict_filetype 对应的文件名 
    '''
    filelist = os.listdir(path) 
    for filename in filelist: 
        filepath = os.path.join(path, filename) 
        # 判断文件夹 
        if os.path.isdir(filepath): 
            # 文件夹继续递归 
            get_filename(filepath, allfile, dict_filetype) 
        else: 
            temp_file_type = filepath.split(".")[-1]
            # 判断文件类型
            if dict_filetype is None or temp_file_type in dict_filetype: 
                allfile.append(filepath) 
            # 展示所有未包含的文件 
            else: 
                print("the file is not include : %s" % filepath ) 
    return allfile      

测试结果:

>>> print(get_filename('.', [], ['java']))
the file is not include : .\service\services1.py
the file is not include : .\test.py
['.\\Solution.java']
>>> print(get_filename('.', []))
['.\\service\\services1.py', '.\\Solution.java', '.\\test.py']

*相关使用函数

  • os.listdir(path) -> list_of_strings
    Return a list containing the names of the entries in the directory.
    path: path of directory to list
    The list is in arbitrary order. It does not include the special entries ‘.’ and ‘…’ even if they are present in the directory.
  • os.path.join()
    Join two or more pathname components, inserting ‘/’ as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.
  • os.path.isdir()
    Return true if the pathname refers to an existing directory.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值