os.walk get directory names
Asked Answered
P

1

13

I have such file structure:

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

and I want to get paths to list in python. So the output would be:

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

I am using such code:

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})

but I cannot figure out how to get directory values.All I get with this code is:

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

How to get the directory without some dirty hacks?

Porcelain answered 6/1, 2013 at 16:5 Comment(0)
K
21

Try

dirname = dirpath.split(os.path.sep)[-1]
Kimon answered 6/1, 2013 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.