vss
vss

Reputation: 607

How to get complete path of files that are being searched within a folder in python?

My folder structure is as follows: Folder Structure

I want to get the paths of all files that contain the string xyz. The result must be as:

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

Answers (1)

Rakesh
Rakesh

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

Related Questions