[英]RegEx to find specific file path
我试图找到文件testing.txt的存在
第一个文件存在于: sub/hbc_cube/college/
第二个文件存在于: sub/hbc/college
但是,在搜索文件所在的位置时,我不能假设字符串“hbc”,因为名称可能因用户而异。 所以我试图找到一种方法
如果路径为PASS
子/_立方体/学院/
如果路径为FAIL
子/*/学院
但是我不能使用 glob 字符 ( ) 因为 ( ) 会将 _cube 视为失败。 我试图找出一个正则表达式,它只会检测一个字符串,而不是一个带下划线的字符串(例如 hbc_cube)。
我曾尝试使用 python regex 字典,但我无法找出要使用的正确正则表达式
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
模块是你的朋友。 您甚至不需要匹配多个目录, 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")
如果不明显, test all("_cube/" in path for path in testfiles)
将满足此要求:
如果文件在两个位置都存在,我只想“失败”打印。 问题是 * 字符正在计算
hbc_cube
。
如果某些匹配的路径不包含_cube
,则测试失败。 由于您想了解导致测试失败的文件,您不能只搜索包含*_cube
的路径中的文件——您必须检索好的和坏的路径,并按所示检查它们。
当然,您可以缩短上述代码,或者根据您的案例的具体情况,通过组合文件夹列表和文件列表等中的选项来将其概括为构建全局路径。
请注意, re
模块提供了“完整的正则表达式”,以及glob
模块使用的更简单的“globs”。 如果你去检查文档,不要混淆它们。
os
模块非常适合于此:
import os
# This assumes your current working directory has sub in it
for root, dirs, files in os.walk('sub'):
for file in files:
if file=='testing.txt':
# print the file and the directory it's in
print(os.path.join(root, file))
os.walk
将在迭代时返回一个三元素元组:根目录、当前文件夹中的目录和当前文件夹中的文件。 要打印目录,请组合根 (cwd) 和文件名。
例如,在我的机器上:
for root, dirs, files in os.walk(os.getcwd()):
for file in files:
if file.endswith('ipynb'):
os.path.join(root, file)
# returns
/Users/mm92400/Salesforce_Repos/DataExplorationClustersAndTime.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationUntitled1.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationExploratory.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationUntitled3.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationUntitled.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationUntitled4.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationUntitled2.ipynb
/Users/mm92400/Salesforce_Repos/DataExplorationClusterAnalysis.ipynb
使用pathlib
解析你的路径,从路径对象获取父级,这将丢弃/college
部分,并检查路径字符串是否以_cube
from pathlib import Path
file_list = lookupfiles(['testing.txt'], dirlist = ['sub/'])
for file in file_list:
path = Path(file)
if str(path.parent).endswith('_cube'):
print('pass')
else:
print('Fail')
编辑:
如果 for 循环中的file
变量包含文件名( sub/_cube/college/testing.txt
),只需在路径上调用 parent 两次, path.parent.parent
另一种方法是过滤lookupfiles()
中的文件, lookupfiles()
是您有权访问该函数并可以对其进行编辑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.