-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathEX15.28.py
43 lines (33 loc) · 1.02 KB
/
EX15.28.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 15.28 (Find words) Write a program that finds all the occurrences of a word in all the
# files under a directory, recursively. Your program should prompt the user to enter
# a directory name.
import os
def main():
path = input("Enter a directory or a file: ").strip()
s = input("Enter a string: ").strip()
# Display the size
try:
findInFile(path, s)
except:
print("File or directory does not exist")
def findInFile(path, word):
try:
if not os.path.isfile(path):
list = os.listdir(path) # All files and subdirectories
for i in range(len(list)):
findInFile(list[i], word) # Recursive call
else: # Base case
findWord(path, word)
except:
print("Let it go")
def findWord(file, word):
try:
infile = open(file, "r")
for line in infile:
if line.find(word) > -1:
print(file + ": " + line)
except:
print("Let is go")
finally:
infile.close()
main()