获取目录树的方法很多,import os
currentDir = 'D:\\115Box\\program\\php'
for dirName, subdirList, fileList in os.walk(currentDir):
print('%s' % dirName)
for fname in fileList:
abspath=dirName+'\\'+fname
print(abspath)
输出如下:
D:\115Box\program\php
D:\115Box\program\php\.metadata
D:\115Box\program\php\.lock
D:\115Box\program\php\.metadata\.mylyn
D:\115Box\program\php\repositories.xml.zip
D:\115Box\program\php\.metadata\.mylyn\contexts
D:\115Box\program\php\.metadata\.plugins
D:\115Box\program\php\.metadata\.plugins\org.eclipse.core.resources
D:\115Box\program\php\.metadata\.plugins\org.eclipse.core.resources\.history\2
===============================================================
实现更多筛选功能的脚本为:import os, fnmatch
def all_files(root, patterns='*', single_level=False, yield_folders=False):
# Expand patterns from semicolon-separated string to list
patterns = patterns.split(';')
for path, subdirs, files in os.walk(root):
if yield_folders:
files.extend(subdirs)
for name in files:
for pattern in patterns:
if fnmatch.fnmatch(name, pattern):
yield os.path.join(path,name)
break
if single_level:
break
thefiles = list(all_files('D:\\115Box\\program\\php\\S3',yield_folders=True))
thefiles.sort()
for i in thefiles:
print (i)
============添加获取文件最近修改时间和写入文件==================import os, fnmatch
import time
time_debug=0
starttime=time.time()
def all_files(root, patterns='*', single_level=False, yield_folders=False):
# Expand patterns from semicolon-separated string to list
patterns = patterns.split(';')
for path, subdirs, files in os.walk(root):
if yield_folders:
files.extend(subdirs)
for name in files:
for pattern in patterns:
if fnmatch.fnmatch(name, pattern):
file1=path+'\\'+name
statinfo=os.stat(file1)
name=name+' '+str(statinfo.st_mtime)
yield os.path.join(path,name)
break
if single_level:
break
thefiles = list(all_files('D:\\115Box\\program\\php\\S3',yield_folders=True))
mediumtime1=time.time()
if (time_debug):
print ("list file used time",mediumtime1-starttime)
thefiles.sort()
mediumtime2=time.time()
if (time_debug):
print ("sort file used time",mediumtime2-mediumtime1)
filelist1=open('D:\\Documents\\Desktop\\work-list.txt','w')
#filelist1.writelines(thefiles)
for i in thefiles:
filelist1.write(i)
filelist1.write("\n")
filelist1.close()
endtime=time.time()
if (time_debug):
print ("write file used time",endtime-mediumtime2)
添加了一个测试时间的debug变量
==============================================================
详细的介绍看官方帮助:
使用 os.walk 方便很多了.这个方法返回的是一个三元
tupple(dirpath, dirnames, filenames),
其中第一个为起始路径,
第二个为起始路径下的文件夹,
第三个是起始路径下的文件.
dirpath是一个string,代表目录的路径,
dirnames是一个list,包含了dirpath下所有子目录的名字,
filenames是一个list,包含了非目录文件的名字.这些名字不包含路径信息,如果需要得到全路径,需要使用 os.path.join(dirpath, name).
help (os.walk)
Help on function walk in module os:
walk(top, topdown=True, οnerrοr=None, followlinks=False)
Directory tree generator.
For each directory in the directory tree rooted at top (including top
itself, but excluding ‘.’ and ‘..’), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’).
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).
If optional arg ‘topdown’ is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down). If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).
When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune
the search, or to impose a specific order of visiting. Modifying
dirnames when topdown is false is ineffective, since the directories in
dirnames have already been generated by the time dirnames itself is
generated.
By default errors from the os.listdir() call are ignored. If
optional arg ‘onerror’ is specified, it should be a function; it
will be called with one argument, an os.error instance. It can
report the error to continue with the walk, or raise the exception
to abort the walk. Note that the filename is available as the
filename attribute of the exception object.
By default, os.walk does not follow symbolic links to subdirectories on
systems that support them. In order to get this functionality, set the
optional argument ‘followlinks’ to true.
Caution: if you pass a relative pathname for top, don’t change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn’t
either.
Example:
import os
from os.path import join, getsize
for root, dirs, files in os.walk(‘python/Lib/email’):
print root, “consumes”,
print sum([getsize(join(root, name)) for name in files]),
print “bytes in”, len(files), “non-directory files”
if ‘CVS’ in dirs:
dirs.remove(‘CVS’) # don’t visit CVS directories