Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.walk get directory names

Tags:

python

os.walk

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?

like image 703
grotos Avatar asked Jan 06 '13 16:01

grotos


People also ask

What is OS walk () in Python?

walk() work in python ? OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). root : Prints out directories only from what you specified.

What is the difference between OS Listdir () and OS walk?

The Python os. listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.

What is a directory walk?

Walking a filesystem means recursively visiting a directory and any sub-directories. It is a fairly common requirement for copying, searching etc.

How do I get a list of directories in Python?

listdir() method in python is used to get the list of all files and directories in the specified directory.


1 Answers

Try

dirname = dirpath.split(os.path.sep)[-1]
like image 160
Andreas Jung Avatar answered Oct 07 '22 10:10

Andreas Jung