• Register

To do it recursively and extract full filenames and directory names, use os.walk and os.path.join:

>>> for root, directories, filenames in os.walk('/tmp/'): 
...     for directory in directories: 
...             print os.path.join(root, directory)  
...     for filename in filenames:  
...             print os.path.join(root,filename)  

To just list the top-level entries:

>>> print os.listdir('/tmp/') 

Now, since the original question asked for "files", you can do a few things:

> Simply ignore the "directories" iterator in os.walk and just iterate over filenames:

>>> for root, directories, filenames in os.walk('/tmp/'): 
...     for filename in filenames:  
...             print os.path.join(root,filename) 

> Use os.path.isfile(path) to test if an item is actually just a regular file or not.

If you want to just pull all files in a top level directory, this little number is usable (note that I usually have most of the common file functions assigned to single-letter variable names in practice, so this is longer than it would be in my normal code:

>>> filenames = [entry for entry in os.listdir("/tmp") if os.path.isfile(os.path.join('/tmp/',entry))] 
188.6K viewsView Upvoters

 

1,760 points
6 1