繁体   English   中英

fnmatch.fnmatch 使用模式排除子目录

[英]fnmatch.fnmatch use a pattern to exclude sub directories

我有这样的目录结构

rootFolder/
    - some.jar
    - another.jar
    subDirectory/
                -some1.jar

我只想获取 rootFolder 而不是 subDirectory 中的文件(some.jar 和 another.jar)。

我也尝试了以下模式,但我试图在没有指定模式中子目录的名称的情况下这样做。 请参阅此处指定目录名称。

我也使用了像'*.jar'这样的模式,但它也包括子目录文件。

有什么建议么?

背景

我正在尝试编写一个用于通过 az cli 上传的通用脚本; 我正在使用的 function 是upload-batch ,它在内部使用 fnmatch,我只能控制使用--pattern标志传递的模式。 这里。

正在使用以下命令:

az storage file upload-batch  --account-name myaccountname --destination dest-directory  --destination-path test/ --source rootFolder --pattern "*.jar" --dryrun

该答案基于原始问题,该问题似乎是一个XY 问题,因为它询问有关使用fnmatch匹配文件名而不是如何为AZ CLI指定模式的问题。

您可以使用re而不是fnmatch

import re
testdata = ['hello.jar', 'foo.jar', 'test/hello.jar', 'test/another/hello.jar', 'hello.html', 'test/another/hello.jaring']
for val in testdata :
    print(val, bool(re.match(r"[^/]*\.jar$", val)))

印刷

hello.jar True                                                                                                                                                                              
foo.jar True                                                                                                                                                                                
test/hello.jar False                                                                                                                                                                        
test/another/hello.jar False                                                                                                                                                                
hello.html False                                                                                                                                                                            
test/another/hello.jaring False                                                                                                                                                             

或为/添加第二次检查

import fnmatch
pattern = '*.jar'
testdata = ['hello.jar', 'foo.jar', 'test/hello.jar', 'test/another/hello.jar', 'hello.html', 'test/another/hello.jaring']
for val in testdata :
    print(val, fnmatch.fnmatch(val, pattern) and not fnmatch.fnmatch(val, '*/*'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM