# -*- coding:UTF-8 -*- """ 遍歷目錄中的全部文件和目錄,並生成全路徑 """ import os target_path = "D:/temp/" ''' path: 遍歷的路徑 file_type: 文件類型列表,若是爲空遍歷全部文件,不爲空遍歷指定文件如[".c", ".h", ".py"]等 ''' def generate_file_list(path, file_type=[]): walks = os.walk(path) for walk in walks: for file in walk[2]: if not file_type: # empty yield walk[0] + "/" + file else: root, ext = os.path.splitext(file) if ext in file_type: yield walk[0] + "/" + file def generate_dir_list(path): walks = os.walk(path) for walk in walks: for dir_name in walk[1]: yield walk[0] + "/" + dir_name for file in generate_file_list(target_path, filetype=[".txt", ".c"]): print(file) # for dir_name in generate_dir_list(target_path): # print(dir_name)