我是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
'''
根据戴维斯·赫林(Davis Herring)在评论中提供的意见。我认为这应该为您工作。
os.path.split()
Python中的方法用于将路径名称拆分为一对头部和尾部。在这里,尾部是最后一个路径名组件,而头是导致该名称的所有内容。例如,考虑以下路径'/home/user/Desktop/file.txt'
HEAD: '/home/user/Desktop/file.txt'
和TAIL: 'file.txt'
os.path.split(fullpath)
将给出这样的输出 (C:\\test1\\tool\\program3\\SETUP3\\reports\\XMLs, 'test1.xml')
注意:如果路径名以斜杠结尾
\
,则tail将为空,如果路径名中没有斜杠,则head为空。
os.path.split()
返回一个元组,其头部位于索引0中,尾部位于索引1中。现在只需解析索引0中的字符串即可获得所需的文件夹。
head_tail=os.split.path(fullpath) #head_tail=('C:\\test1\\tool\\program3\\SETUP3\\reports\\XMLs', 'test1.xml')
folder=head_tail[0].split('\\') #head_tail[0]='C:\\test1\\tool\\program3\\SETUP3\\reports\\XMLs'
#folder=['C:', 'test1', 'tool', 'Program1', 'SETUP1', 'reports', 'XMLs', 'test1.xml']
print(folder[3],end=",")
现在输出将打印出来program1
。将此作为函数。将所有路径传递给函数,您的输出将看起来像您想要的,即Program1, program 2, program3,
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句