9

私はそのようなファイル構造を持っています:

d:\temp\random1\index.html
d:\temp\random2\index.html
d:\temp\random3\index.html

Pythonでリストへのパスを取得したいと思います。したがって、出力は次のようになります。

files = ['path': 'd:\temp\random1\index.html', 'directory': 'random1']

私はそのようなコードを使用しています:

files = []
for dirpath, dirnames, filenames in os.walk('D:\\temp'):
    for fname in filenames:
        if fname.endswith(".md"):
            path = os.path.join(dirpath,fname)
            files.append({'path':path,'directory': dirpath})

しかし、ディレクトリ値を取得する方法がわかりません。このコードで取得できるのは次のとおりです。

files = ['path': 'd:\temp\random1\index.html', 'directory': 'd:\temp\random1\']

いくつかの汚いハックなしでディレクトリを取得する方法は?

4

1 に答える 1

15

試す

dirname = dirpath.split(os.path.sep)[-1]
于 2013-01-06T16:13:04.057 に答える