[파이썬] os 경로 패턴 매칭: `os.fnmatch()`

In Python, the os.fnmatch() function is a useful tool for matching file or directory names using Unix shell-style wildcard patterns. This function can be used to perform pattern matching on file paths or directory paths in a platform-independent manner.

Syntax

The syntax of os.fnmatch() is as follows:

os.fnmatch(name, pattern)

Here, name is the name of the file or directory path that you want to match, and pattern is the Unix shell-style wildcard pattern you want to use.

Wildcard Patterns

Wildcard patterns are a way of expressing a pattern with the help of special characters. Some widely used wildcard characters are:

Example Usages

Let’s take a look at some examples to understand how os.fnmatch() can be used.

  1. Matching file extensions:
import os

files = ["hello.txt", "world.json", "code.py", "notes.txt"]

for file in files:
    if os.fnmatch(file, "*.txt"):
        print(f"Matched: {file}")

Output:

Matched: hello.txt
Matched: notes.txt
  1. Matching files with a specific prefix:
import os

files = ["hello.txt", "world.json", "code.py", "notes.txt"]

for file in files:
    if os.fnmatch(file, "hello*"):
        print(f"Matched: {file}")

Output:

Matched: hello.txt
  1. Matching directories with a specific pattern:
import os

directories = ["/path/to/dir1", "/path/to/dir2", "/path/to/dir3"]

for directory in directories:
    if os.path.isdir(directory) and os.fnmatch(directory, "/path/to/*"):
        print(f"Matched: {directory}")

Output:

Matched: /path/to/dir1
Matched: /path/to/dir2
Matched: /path/to/dir3

Note: In the third example, we use os.path.isdir() to check if the given path is a directory before applying the pattern matching.

Conclusion

The os.fnmatch() function in Python provides a convenient way to perform pattern matching on file and directory names using Unix shell-style wildcard patterns. It is a powerful tool for filtering and selecting specific files or directories based on their names. Incorporating os.fnmatch() in your code can help you automate tasks that involve working with file or directory paths.