Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List only files in a directory?

Tags:

python

Is there a way to list the files (not directories) in a directory with Python? I know I could use os.listdir and a loop of os.path.isfile()s, but if there's something simpler (like a function os.path.listfilesindir or something), it would probably be better.

like image 494
tkbx Avatar asked Jan 05 '13 20:01

tkbx


People also ask

How do I show only file names in a directory?

/W - Displays only filenames and directory names (without the added information about each file) in a five-wide display format. dir c:*. This form of the DIR command will also display directories. They can be identified by the DIR label that follows the directory name.

How do I list files in a directory in command prompt?

You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.


2 Answers

This is a simple generator expression:

files = (file for file in os.listdir(path)           if os.path.isfile(os.path.join(path, file))) for file in files: # You could shorten this to one line, but it runs on a bit.     ... 

Or you could make a generator function if it suited you better:

def files(path):     for file in os.listdir(path):         if os.path.isfile(os.path.join(path, file)):             yield file 

Then simply:

for file in files(path):     ... 
like image 53
Gareth Latty Avatar answered Sep 17 '22 18:09

Gareth Latty


files = next(os.walk('..'))[2] 
like image 44
johnson Avatar answered Sep 17 '22 18:09

johnson