Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list directory, subdirectory, and files

Tags:

python

file

path

I'm trying to make a script to list all directory, subdirectory, and files in a given directory.
I tried this:

import sys,os  root = "/home/patate/directory/" path = os.path.join(root, "targetdirectory")  for r,d,f in os.walk(path):     for file in f:         print os.path.join(root,file) 

Unfortunatly it doesn't work properly.
I get all the files, but not their complete paths.

For example if the dir struct would be:

 /home/patate/directory/targetdirectory/123/456/789/file.txt 

It would print:

 /home/patate/directory/targetdirectory/file.txt 

What I need is the first result. Any help would be greatly appreciated! Thanks.

like image 474
thomytheyon Avatar asked May 26 '10 03:05

thomytheyon


People also ask

How do I get a list of files in a directory and subdirectories?

The dir command displays a list of files and subdirectories in a directory. With the /S option, it recurses subdirectories and lists their contents as well.

How do I get a list of subfolders in Python?

listdir() function. A simple solution to list all subdirectories in a directory is using the os. listdir() function. However, this returns the list of all files and subdirectories in the root directory.

How do I get a list of directories in Python?

path. join() and you will get the full path directly (if you wish), you can do this in Python 3.5 and above. Returns a list of all subfolders with their full paths. This again is faster than os.


2 Answers

Use os.path.join to concatenate the directory and file name:

for path, subdirs, files in os.walk(root):     for name in files:         print(os.path.join(path, name)) 

Note the usage of path and not root in the concatenation, since using root would be incorrect.


In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join would be:

pathlib.PurePath(path, name) 

The advantage of pathlib is that you can use a variety of useful methods on paths. If you use the concrete Path variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.

like image 65
Eli Bendersky Avatar answered Sep 21 '22 18:09

Eli Bendersky


Just in case... Getting all files in the directory and subdirectories matching some pattern (*.py for example):

import os from fnmatch import fnmatch  root = '/some/directory' pattern = "*.py"  for path, subdirs, files in os.walk(root):     for name in files:         if fnmatch(name, pattern):             print os.path.join(path, name) 
like image 22
Ivan Avatar answered Sep 20 '22 18:09

Ivan