如何获取Python中“globbed”的值

2024-09-28 01:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码将我感兴趣的文件路径的两部分连接起来:

import glob

prefix = /aldo/programs/info
suffix = /final/*_cube/myFile.txt

prefix = prefix.rstrip()

file = glob.glob(prefix+'/final/*_cube/myFile.txt')

print (file)

打印最终文件给了我:

/aldo/programs/info/final/Michael_cube/myFile.txt

这是好的和有意的。但是,我试图将全局化的字符串设置为变量,在本例中,“Michael”。我尝试过使用正则表达式,但找不到一种方法来获取globbed的值(Michael)。我很困,任何指导都将不胜感激


Tags: 文件代码路径infotxtprefixmyfileglob
2条回答

DEMO

^.*?\/final\/(.*?)_cube\/myFile\.txt$

您可以从组1获取内容,或者用替换字符串$1替换整个匹配项以获得输出

说明:
^$开始和结束patren需要模式匹配整行。您可以用“match all”量词来解释数据中的任何未知数。.*?,然后您所需要做的就是用一个捕获组获取所需的输出

您可以使用字符串切片,从结果中获得所有需要剥离的部分,以获得作为*-值提供的内容:

import glob

prefix = "/aldo/programs/info"
s0,g,s1 = "/final/", "*", "_cube/myFile.txt" # split the parts around the * 
suffix = s0+g+s1                             # and recombinate
prefix = prefix.rstrip()

file = glob.glob(prefix+'/final/*_cube/myFile.txt')

name = "/aldo/programs/info/final/Michael_cube/myFile.txt"

# slice: len(prefix+s0) starting and stopping at -len(s1)
print(name[len(prefix+s0):-len(s1)]) 

输出:

Michael

相关问题 更多 >

    热门问题