fnmatch.fnmatch use a pattern to exclude sub directories

858 Views Asked by At

I have a directory structure like this

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

I only want to get the files in the rootFolder and not the subDirectory (some.jar and another.jar).

I have also tried the following pattern but I was trying to do it without specifying the name of the subDirectory in the pattern. See here with directory name specified.

I have also used pattern like '*.jar' but it also includes the subDirectory file.

Any suggestions?

Background

I am trying to write a generic script for uploading via az cli; the function I am using is upload-batch and it internally uses fnmatch where I only have control of the pattern I pass using the --pattern flag. See here.

Below command is being used:

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

There are 1 best solutions below

1
On

This answer is based on the original question which seems to be an XY problem as it asked about matching file names using fnmatch instead of how to specify a pattern for the AZ CLI.

You could use re instead of 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)))

prints

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

or add a second check for /

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, '*/*'))