Write a Python program to list all the files in the given directory
Hey! In this article, you will learn how to get the list of all files and folders in a given directory using a simple Python code. We will learn about the Operating system module to implement the program.
We need to import the module os in order to use different methods of the os module in our program using the below statement.
import os
listdir() in Operating System (os) Module
As the name of the module suggests the os module provides different functions to interact with the operating system.
In this article, we are going to use listdir() method to get the list of all files in a given directory.
listdir()
Syntax:
os.listdir(path)
The method takes a path of the directory as an argument. Here the path is an object representing file system path.
It can be either string or byte object. As a directory path contains escape sequence, we use raw string as we should ignore the escape codes.
If we use byte string, the method listdir(), returns a list of entries in a directory as byte strings.
os.listdir(path) returns a list of filenames of the directory specified by the path.
Now let us understand the method listdir() using examples.
Example 1
import os path = r'D:\programs\j'#here you can use your own directory path list_of_files = os.listdir(path) for file in list_of_files: print(file)
Output:
B.class BankAccount.class BMI.class BMI.java Box.class Boxdetails.class Boxdetails.java
In the output, we got all the files in the directory path D:\programs\j in my PC.
Now, let us look another program where we use byte string for the variable path.
Example 2
import os path = b'D:\programs\j'#Here you use your own directory path list_of_files = os.listdir(path) for file in list_of_files: print(file)
Output:
b'B.class' b'BankAccount.class' b'BMI.class' b'BMI.java' b'Box.class' b'Boxdetails.class' b'Boxdetails.java'
In the above output, for the same directory path of byte string, we got all the files as byte strings.
Hurrah! In this article, we have learned how to use python to get the entries of the files present in a particular directory.
Thank you for reading the article. I hope it helped you someway. Also, do check out our other related articles below:
Leave a Reply