In the following programs you will learn that how to search specific file in directories. In Python programming we can use listdir() function of 'os' library to list all directories on specific path.
name = input("Enter directory and file name: ")
fobj = open(name) #user enter File Name and directory assigning to 'fobj'.
print(fobj.read()) #and printing.
fobj.close() #Closing File.
import os
for filename in os.listdir("C://"): #loop looping on Given
print(filename) #directory and printing.
import os
#open files in directory.
path = "C://"
dirs = os.listdir(path)
# print the files in given directory.
for file in dirs: #loop looping on given Directories.
print(file) #and printing.
import os
for top, dirs, files in os.walk("C://"): #loop looping on Data.
for nm in files: #loop looping on All Directories and Files
print(os.path.join(top, nm)) #and printing.
import os
path = "C://"
for dirname, dirnames, filenames in os.walk(path):
# print path to all filenames with extension txt.
for filename in filenames:
fname_path = os.path.join(dirname, filename)
fext = os.path.splitext(fname_path)[1]
if fext == ".txt": #if file found then
print(fname_path) #print file name.
else: #if not then
continue #continue searching.