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.

你可能感兴趣的:(Python,面试,python,开发语言,后端)