Reputation: 607
My folder structure is as follows:
I want to get the paths of all files that contain the string xyz. The result must be as:
folder/folderA/fileA2
folder/folderB/fileB1
folder/file1
I tried this:
for path, subdirs, files in os.walk(folderTestPath):
for file in files:
if "xyz" in open(folderTestPath+file,'r'):
print (os.path.abspath(file))
folderTestPath contains the path of the folder. This code only gives me the file names followed by a file not found error. I know this is a simple thing, but for some reason am unable to get it. Please help.
Upvotes: 0
Views: 60
Reputation: 82765
You can use the os.path.join method:
for path, subdirs, files in os.walk(folderTestPath):
for file in files:
filePath = os.path.join(path, file)
if "xyz" in open(filePath ,'r').read():
print("xyz")
print(filePath)
As Eric mentioned to close the file after reading it use the below snippet:
import os
for path, subdirs, files in os.walk(folderTestPath):
for file in files:
filePath = os.path.join(path, file)
with open(filePath ,'r') as data:
if "xyz" in data.read():
print("xyz")
print(filePath)
data.close()
Upvotes: 1