适用于Python的Directory Walker [英] Directory Walker for Python

查看:96
本文介绍了适用于Python的Directory Walker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在此处使用目录浏览器

I am currently using the directory walker from 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

此较小的更改使您可以在文件中拥有完整路径.

This minor change allows you to have the full path within the file.

有人可以帮助我如何使用此方法查找文件名吗?我既需要完整路径,也需要文件名.

Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.

推荐答案

而不是使用'.作为目录,请参考其绝对路径:

Rather than using '.' as your directory, refer to its absolute path:

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

此外,我建议使用'file'以外的其他词,因为这意味着python语言中的某些内容.不是关键字,尽管如此它仍然可以运行.

Also, I'd recommend using a word other than 'file', because it means something in the python language. Not a keyword, though so it still runs.

顺便说一句,在处理文件名时,我发现os.path模块非常有用-我建议仔细检查一下,尤其是

As an aside, when dealing with filenames, I find the os.path module to be incredibly useful - I'd recommend having a look through that, especially

os.path.normpath

标准化路径(摆脱多余的."和"theFolderYouWereJustIn/../")

Normalises paths (gets rid of redundant '.'s and 'theFolderYouWereJustIn/../'s)

os.path.join

加入两条路径

这篇关于适用于Python的Directory Walker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆