2009-04-22 41 views
5

我目前使用的目录沃克Here目录沃克为Python

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 

这一个小小的改变可以让你有文件中的完整路径。

任何人都可以帮助我如何使用它找到文件名吗?我需要完整路径和文件名。

+0

任何人都可以帮助我如何找到文件名以及使用它吗?我需要完整路径和文件名。 – Specto 2009-04-22 04:34:48

+0

print os.path.basename(file) – anon58192932 2013-05-05 06:10:33

回答

6

而不是使用'。'为您的目录,请参阅其绝对路径:

for file in DirectoryWalker(os.path.abspath('.')): 
    print file 

此外,我推荐使用比“文件”等词,因为这意味着在Python语言的东西。不是关键字,尽管它仍然运行。

顺便说一句,与文件名打交道时,我找到了os.path中模块是非常有用的 - 我建议其通过一看,尤其是

os.path.normpath 

正常化路径(摆脱多余的”。'和'theFolderYouWereJustIn /../的)

os.path.join 

连接两个路径

0

只是在前面加上当前目录路径返回的 “./foo” 路径:

print os.path.join(os.getcwd(), file) 
1

os.path.dirname()? os.path.normpath()? os.path.abspath则()?

这也是一个可以考虑递归的地方。

12

你为什么要自己做这样无聊的事情?

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'