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 Files\Java','java')

file_writer = open('list.txt','w',encoding='utf-8')
for file in file_lists:
    file_writer.write("%s\n"%file)
file_writer.close()

 

posted @ 2016-05-20 18:58  你好阿汤哥  Views(457)  Comments(0Edit  收藏  举报