简体   繁体   中英

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

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM