您的位置:首页 > 其它

遍历目录中的所有文件和目录,并生成全路径

2015-06-30 23:08 435 查看
# -*- 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: