在特定扩展名的文件中搜索字符串后提取文件夹名称

问题描述 投票:1回答:1

我是python编程的新手。在尝试对特定扩展名的文件中的字符串进行递归搜索后,我正在尝试制作工具来提取程序名称(文件夹名称)

我在打印具有要在xml文件中搜索的字符串的文件的路径后,得到了这样的数据。现在我要提取程序名称,例如Program1,program 2,program

import os
search_path = input("Enter directory path to search : ")

for folder, dirs, files in os.walk(search_path):
    for file in files:
        if file.endswith('.xml'):
            fullpath = os.path.join(folder, file)  
            with open(fullpath, 'r') as f:
                for line in f:
                    if "test" in line:
                        print(fullpath)

output is like
C:\test1\tool\Program1\SETUP1\reports\XMLs\test1.xml
C:\test1\tool\Program1\SETUP1\reports\XMLs\test1.xml
C:\test1\tool\Program1\SETUP1\reports\XMLs\test1.xml
C:\test1\tool\program2\SETUP2\reports\XMLs\test2.xml
C:\test1\tool\program2\SETUP2\reports\XMLs\test2.xml
C:\test1\tool\program3\SETUP3\reports\XMLs\test2.xml
C:\test1\tool\program3\SETUP3\reports\XMLs\test3.xml
C:\test1\tool\program3\SETUP3\reports\XMLs\test3.xml
data
i want to extract the program name and setup  from above data 
'''

我是python编程的新手。我试图做一个工具来递归搜索特定扩展名的文件中的字符串后提取程序名称(文件夹名称),我在...

python string file search directory
1个回答
0
投票

来自注释中Davis Herring给定的输入。我认为这应该对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.