#coding=utf-8
import os,sys
reload(sys)
sys.setdefaultencoding("utf-8")
def scan_files_sub_dir(directory,prefix=None,postfix=None):
files_list=[]
for root, sub_dirs, files in os.walk(directory):
for special_file in files:
if postfix:
if special_file.endswith(postfix):
files_list.append(os.path.join(root,special_file))
elif prefix:
if special_file.startswith(prefix):
files_list.append(os.path.join(root,special_file))
else:
files_list.append(os.path.join(root,special_file))
return files_list
files = scan_files_sub_dir(".",None,".txt")
print files def scan_files(directory,prefix=None,postfix=None):
files_list=[]
for file in os.listdir(directory):
if postfix:
if file.endswith(postfix):
files_list.append(file)
elif prefix:
if file.startswith(prefix):
files_list.append(file)
else:
files_list.append(file)
return files_list
files = scan_files(".",None,".txt")
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()
05-07 15:12
查看更多