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:
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:
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:
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:
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:
Here is the another remaining screenshot of the above one:
You may also like to learn or practice the same program in other popular programming languages: