codescracker


python

Python Program to List all Files in Directory



« Previous Program Next Program »


List all Files in Directory in Python

To list all the files present in the directory given by the user in python, first import os and glob library and then use os.chdir() to get the desired directory and then use glob.glob() to find all the files present inside that directory as shown in the program given below:

Python Programming Code to List all Files in Directory

Following python program list all the files present in the C:/Python34 directory:

# Python Program - List All Files in Directory
		
import glob, os
os.chdir("C:/Python34")
for file in glob.glob("*.*"):
    print(file)

Here is the sample run of the above python program to illustrate how to list and print all the files present in any directory:

python list files in directory

To list only textual file (all files with only .txt extension), then replace *.* with *.txt. Here is the program to list all textual files present inside the current directory that is C:/Python34

# Python Program - List .txt Files in Directory
		
import glob, os
os.chdir("C:/Python34")
for file in glob.glob("*.txt"):
    print(file)

If you will run the above program, then you will see the following output:

list files in directory python

Now let's modify the above program and allow user to enter their own required directory to list all the files from it:

# Python Program - List .txt Files in Directory
		
import glob, os;
directory = input("Enter directory to list all files it contains: ");
os.chdir(directory);
for file in glob.glob("*.*"):
    print(file);

Here is the initial output produced after running the above program:

list all files in directory python

Now enter any directory to list all the files present inside it say C:\TurboC4\TC\BIN and press enter key to see all the files present inside the directory C:\TurboC4\TC\BIN as shown in below sample run:

python program list all files

Here is the another remaining screenshot of the above one:

python program list files in directory

Program Video with Compile and Run

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test