Searching File and Listing Directories in Python

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.

Program User Entered File Name File Reading

Program

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.
Output
Enter directory and file name: C://MyTxtFile.txt
The is line 1 text in MyTxtFile file
The is line 2 text in MyTxtFile file

Program Listing All Folders of Given Directory

Program

import os
for filename in os.listdir("C://"): #loop looping on Given
    print(filename) #directory and printing.
Output
$RECYCLE.BIN
$WINDOWS.~BT
$Windows.~WS
1
BC5
BDE32
bootTel.dat
Documents and Settings
ESD
hiberfil.sys
Intel
MSOCache
MyFolder2
MyTxtFile.txt
Program Files
Program Files (x86)
ProgramData
Python34
Recovery
swapfile.sys
System Volume Information
Temp
test
Users
wamp64
Windows

Program Listing All Folders of Given Directory Another Method

Program

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.
Output
$RECYCLE.BIN
$WINDOWS.~BT
$Windows.~WS
1
BC5
BDE32
bootTel.dat
Documents and Settings
ESD
hiberfil.sys
Intel
MSOCache
MyFolder2
MyTxtFile.txt
Program Files
Program Files (x86)
ProgramData
Python34
Recovery
swapfile.sys
System Volume Information
Temp
test
Users
wamp64
Windows

Program Printing All Files and Folders on Given Directory
Program

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.
Output
C://bootTel.dat
C://hiberfil.sys
C://MyTxtFile.txt
C://swapfile.sys
C://$RECYCLE.BIN\S-1-5-21-2029070420-582233655-1001\$I41FH09
C://$RECYCLE.BIN\S-1-5-21-2029070420-582233655-1001\$I4Z3N0D.lnk
C://$RECYCLE.BIN\S-1-5-21-2029070420-582233655-1001\$I72E772.exe
C://$RECYCLE.BIN\S-1-5-21-761997063-582233655-1001\$I77VX8L.zip
.
.
.

Program Searching File in Given Directory
Program

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.
Output
C://MyTxtFile.txt
C://1\tags_frequency.txt
C://BC5\DOC\addon.txt
C://BC5\DOC\config.txt
C://BC5\DOC\intldemo.txt
C://BC5\DOC\ole_errs.txt
C://BC5\DOC\owl5.txt
C://BC5\DOC\pe.txt
C://BC5\DOC\redist.txt
.
.
.