I was working on a small script in Python where I had to traverse through the directories which have multiple types of files, but I want to open only text files. So how can I do that? Below is my code.
import os,re
pat=re.compile(input("Enter the text you want to search for : "))
fpath=r'C:\Users\Python\Python_my_Scripts\'
for i in os.walk(fpath):
for fname in i[-1]:
fpath=os.path.join(i[0],fname)
try:
IN=open(fpath,"r")
except Exception as e:
print(e)
else:
line_num=0
for line in IN:
line_num+=1
if not re.search(r'^\s+#',line):
if re.search(pat, line):
print("{1:>2d} : {0}".format(fpath,line_num))
The code basically breaks in the try segment if a directory contains any non-text file.