DEV Community

Cover image for How to list all files of a directory in python
FlutterCorner
FlutterCorner

Posted on

How to list all files of a directory in python

Hello Guys How are you all? Hope You all are fine Today in this tutorial We are going to talk About How to list all files of a directory in python So lets get start this tutorial without wasting your time. Here we will Talk About All Possibles Method. Lets learn one by one.

How to list all files of a directory in python

Method 1: Using os.listdir()

os.listdir() will get you everything that’s in a directory – files and directories.

If you want just files, you could either filter this down using os.path:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
Enter fullscreen mode Exit fullscreen mode

For Example
With listdir in os module you get the files and the folders in the current dir

 import os
 arr = os.listdir()
 print(arr)

 >>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
Enter fullscreen mode Exit fullscreen mode

Looking in a directory

arr = os.listdir('c:\\files')
Enter fullscreen mode Exit fullscreen mode

Method 2: Using os.walk()

use os.walk() which will yield two lists for each directory it visits – splitting into files and dirs for you. If you only want the top directory you can break the first time it yields

Here Is All Possible Methods with Example How to list all files of a directory in python

Top comments (0)