Reputation: 11
I want to search "word" in many files in a folder.
I have already :
route=os.listdir("/home/new")
for file in route:
This does not work :
f = open ('' , 'r')
for line in f :
I tried this :
for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
but I have an error :
f=open( file ,'r')
IOError: [Errno 2] No such file or directory: file.txt
When I delete file.txt, next file , I receive the same error.
Upvotes: 1
Views: 3846
Reputation: 5232
How about something along these lines?
import os
folderpath = "/.../.../foldertosearch"
word = 'giraffe'
for(path, dirs, files) in os.walk(folderpath, topdown=True):
for filename in files:
filepath = os.path.join(path, filename)
with open(filepath, 'r') as currentfile:
for line in currentfile:
if word in line:
print(
'Found the word in ' + filename + ' in line ' +
line
)
Upvotes: 2
Reputation: 155353
os.listdir
only returns the file names, not the qualified paths. So to make this work, your open
needs to be opening the qualified path (constructed with os.path.join("/home/new", file)
), not just file
.
Upvotes: 0
Reputation: 809
for file in filelist:
f = open(file,"r")
data = f.read()
rows = data.split("\n")
count = 0
full_data = []
for row in rows:
split_row = row.split(",")
full_data.append(split_row)
for each in full_data:
if re.search("word", each) is not None:
count += 1
Something like this, although your question is not at all specific about whether you want to count, return where word was found, change word to something, etc. so feel free to edit it as you see fit
(This code works for .csv as you can probably tell)
Upvotes: 0