I have a folder "A" and many files within it ( say 100 ). I want to open the all these files(all are text files) and count the number of times the word "virtual memory" is present in all of them [Either the total sum or the number of times present in each file] I tried something like this but not able to achieve the same.
path = 'MY_PATH'
count=0
filecount=0
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
files.append(os.path.join(r, file))
print(files)
for fileList in files:
with open(fileList, "r") as f:
# text = f.read()
# print(len(text))
print('OPENING FILE: ',f)
for word in f:
#print(word)
if(word == 'virtual memory'):
print('WORD FOUND')
count+=1
print("COUNT : ", count)
Is there any quick script which I could use to execute the above query or some corrections I need to make? Thanks in advance!
Use file.count
to count the number of a phrase in a txt
file. Here a simple implementation how you can do this:
import os
path = 'MY_PATH'
count= 0
for root, dirs, files in os.walk(path):
for file in files:
num=0
with open(os.path.join(root, file),"r") as f:
f_reader =f.read()
team = 'virtual memory'
num = f_reader.count(team)
count+=num
print('OPENING FILE: ',file, ' - Count:', num)
print("COUNT : ", count)