简体   繁体   中英

Using fnmatch to match 2 parts of a file name

I am currently using fnmatch to find the files that I want to copy and to ignore the rest:

Below is some of my script just to give an example of how it's used.

pattern = "*.xlsx"

if fnmatch(name, pattern):
    source_files.append(os.path.join(path, name))

What I've realised is that this is currently also matching hidden files, which I don't want copied.

I see 3 options for solving this problem:

  1. I could either exclude hidden files as a whole.
  2. I could exclude files that begin with ~$ .
  3. Or I could only choose files that begin with Update and end with .xlsx

I feel that the easiest way to describe the type of files I want to copy is with regex but I don't think fnmatch accepts full regex.

What would you recommend?

Use fnmatch 's ability to exclude certain characters, also specified in the docs

In [33]: fnmatch('hello.xlsx', '[!~]*.xlsx')
Out[33]: True

In [34]: fnmatch('~hello.xlsx', '[!~]*.xlsx')
Out[34]: False

And as for the last comment in your question - if you feel the best way to describe your file is with regex, why not replace fnmatch with re.match(...) is not None ? Do you have to use fnmatch ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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