zoukankan      html  css  js  c++  java
  • Python 扫面文件夹中的文件

     1 #coding=utf-8
     2 import os,sys
     3 reload(sys)
     4 sys.setdefaultencoding("utf-8")
     5 def scan_files_sub_dir(directory,prefix=None,postfix=None):
     6     files_list=[]
     7     for root, sub_dirs, files in os.walk(directory):
     8         for special_file in files:
     9             if postfix:
    10                 if special_file.endswith(postfix):
    11                     files_list.append(os.path.join(root,special_file))
    12             elif prefix:
    13                 if special_file.startswith(prefix):
    14                     files_list.append(os.path.join(root,special_file))
    15             else:
    16                 files_list.append(os.path.join(root,special_file)) 
    17     return files_list
    18 files  = scan_files_sub_dir(".",None,".txt")
    19 print files
    20 
    21 def scan_files(directory,prefix=None,postfix=None):
    22     files_list=[]
    23     for file in os.listdir(directory):
    24         if postfix:
    25                 if file.endswith(postfix):
    26                     files_list.append(file)
    27         elif prefix:
    28             if file.startswith(prefix):
    29                 files_list.append(file)
    30         else:
    31             files_list.append(file) 
    32     return files_list
    33 files  = scan_files(".",None,".txt")
    34 print files

     另一种方法:

    import os
    def get_file_lists(init_dir,postfix=None):
        file_lists = []
        if not os.path.exists(init_dir):
            print('%s not exist'%init_dir)
            return file_lists
        if not os.path.isdir(init_dir):
            print('%s not dir'%init_dir)
            return file_lists
        for file in os.listdir(init_dir):
            path = "%s\%s"%(init_dir,file)
            if postfix and not file.endswith(postfix) and os.path.isfile(path):
                continue
            if not os.path.isdir(path):
                file_lists.append(path)
            if os.path.isdir(path):
                file_lists.extend(get_file_lists(path,postfix))
        return file_lists
    
    file_lists = get_file_lists(r'D:Program FilesJava','java')
    
    file_writer = open('list.txt','w',encoding='utf-8')
    for file in file_lists:
        file_writer.write("%s
    "%file)
    file_writer.close()
  • 相关阅读:
    调用百度地图API添加点聚合时,marker标注的label标签刷新丢失问题
    redis--基本命令
    centos8安装redis6.0.5
    centos8更改镜像源
    centos8重启网络服务
    搭建eureka高可用
    html5图片缩放后上传blob
    mysql主从复制
    zTree
    datetimepicker使用总结
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/5513206.html
Copyright © 2011-2022 走看看