Python3遍历目录树实现方法

WBOY
Release: 2016-06-10 15:11:47
Original
1224 people have browsed it

本文实例讲述了Python3遍历目录树的方法。分享给大家供大家参考。具体实现方法如下:

import os, fnmatch
# 检查一个目录,后者某个包含子目录的目录树,并根据某种模式迭代所有文件
# patterns如:*.html,若大小写敏感可写*.[Hh][Tt][Mm][Ll] 
# single_level 为True表示只检查第一层 
# yield_folders 表示是否显示子目录,为False只遍历子目录中的文件,
# 但不返回字母名 
def all_files(root, patterns='*', single_level=False, yield_folders=False): 
  # 将模式从字符串中取出放入列表中 
  patterns = patterns.split(';') 
  for path, subdirs, files in os.walk(root): 
    if yield_folders: 
      files.extend(subdirs) 
    files.sort() 
    for name in files: 
      for pattern in patterns: 
        if fnmatch.fnmatch(name, pattern): 
          yield os.path.join(path, name) 
          break 
    if single_level: 
      break 
for file in all_files('d:\\pm', '*.s;*.c', False, False):
  print(file) 

Copy after login

希望本文所述对大家的Python3程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!