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))]
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']
Looking in a directory
arr = os.listdir('c:\\files')
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)