我目前使用的是来自Here的目录遍历程序
import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
return fullname
for file in DirectoryWalker(os.path.abspath('.')):
print file这一微小的更改允许您拥有文件中的完整路径。
有没有人能告诉我如何使用这个来查找文件名?我需要完整的路径和文件名。
发布于 2009-04-22 00:26:32
而不是使用'.‘作为您的目录,请参考其绝对路径:
for file in DirectoryWalker(os.path.abspath('.')):
print file另外,我建议使用'file‘以外的词,因为它在python语言中的意思是什么。不是一个关键字,所以它仍然可以运行。
顺便说一句,在处理文件名时,我发现os.path模块非常有用--我建议您仔细研究一下,尤其是
os.path.normpath规格化路径(去掉多余的‘.’和‘theFolderYouWereJustIn/../’)
os.path.join连接两条路径
发布于 2009-04-22 17:40:33
你为什么要自己做这么无聊的事情呢?
for path, directories, files in os.walk('.'):
print 'ls %r' % path
for directory in directories:
print ' d%r' % directory
for filename in files:
print ' -%r' % filename输出:
'.'
d'finction'
d'.hg'
-'setup.py'
-'.hgignore'
'./finction'
-'finction'
-'cdg.pyc'
-'util.pyc'
-'cdg.py'
-'util.py'
-'__init__.pyc'
-'__init__.py'
'./.hg'
d'store'
-'hgrc'
-'requires'
-'00changelog.i'
-'undo.branch'
-'dirstate'
-'undo.dirstate'
-'branch'
'./.hg/store'
d'data'
-'undo'
-'00changelog.i'
-'00manifest.i'
'./.hg/store/data'
d'finction'
-'.hgignore.i'
-'setup.py.i'
'./.hg/store/data/finction'
-'util.py.i'
-'cdg.py.i'
-'finction.i'
-'____init____.py.i'但是如果你坚持,在os.path中有路径相关的工具,os.basename就是你所看到的。
>>> import os.path
>>> os.path.basename('/hello/world.h')
'world.h'发布于 2009-04-22 00:27:33
os.path.dirname()?os.path.normpath()?os.path.abspath()?
这也是一个思考递归的好地方。
https://stackoverflow.com/questions/775231
复制相似问题