Directory Walker for Python

≡放荡痞女 提交于 2019-11-30 09:57:32

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

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

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.

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

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

os.path.join

Joins two paths

Why do you want to do such boring thing yourself?

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

Output:

'.'
    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'

But if you insist, there's path related tools in os.path, os.basename is what you are looking at.

>>> import os.path
>>> os.path.basename('/hello/world.h')
'world.h'

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

This would also be a lovely place to think recursion.

Just prepend the current directory path to the "./foo" path returned:

print os.path.join(os.getcwd(), file)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!