gpt4 book ai didi

python - 正则表达式查找特定文件路径

转载 作者:行者123 更新时间:2023-12-01 08:08:37 25 4
gpt4 key购买 nike

我正在尝试查找文件testing.txt是否存在

第一个文件存在于:sub/hbc_cube/college/

第二个文件存在于:sub/hbc/college

但是,当搜索文件存在的位置时,我不能假设字符串“hbc”,因为名称可能因用户而异。所以我想找到一种方法

通过(如果路径为)

sub/_cube/college/

失败(如果路径为

)

sub/*/college

但我不能使用全局字符 (),因为 () 会将 _cube 视为失败。我正在尝试找出一个仅检测字符串而不检测带下划线的字符串(例如 hbc_cube)的正则表达式。

我尝试使用 python 正则表达式字典,但我无法找出要使用的正确正则表达式

file_list = lookupfiles(['testing.txt'], dirlist = ['sub/'])
for file in file_list:
if str(file).find('_cube/college/') #hbc_cube/college
print("pass")
if str(file).find('*/college/') #hbc/college
print("fail")

如果文件存在于两个位置,我只想“失败”打印。问题是 * 字符正在计算 hbc_cube。

最佳答案

glob 模块是你的 friend 。您甚至不需要匹配多个目录,glob 会为您完成:

from glob import glob

testfiles = glob("sub/*/testing.txt")

if len(testfiles) > 0 and all("_cube/" in path for path in testfiles):
print("Pass")
else:
print("Fail")

如果不明显,测试 all("_cube/"in path for path in testfiles) 将满足此要求:

If the file exists in both locations I want only "fail" to print. The problem is the * character is counting hbc_cube.

如果某些匹配的路径不包含_cube,则测试失败。由于您想了解导致测试失败的文件,因此您不能仅搜索包含 *_cube 的路径中的文件 - 您必须检索好路径和坏路径,并如图所示检查它们。

当然,您可以缩短上述代码,或者将其概括为通过组合文件夹列表和文件列表等中的选项来构造全局路径,具体取决于您的情况的具体情况。

请注意,有由 re 模块提供的“完整正则表达式”,以及由 glob 模块使用的更简单的“glob”。如果您去查看文档,请不要混淆它们。

关于python - 正则表达式查找特定文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com