[New-bugs-announce] [issue38144] Add the root_dir and dir_fd parameters in glob.glob()

Serhiy Storchaka report at bugs.python.org
Thu Sep 12 14:31:01 EDT 2019

New submission from Serhiy Storchaka <storchaka+cpython at gmail.com>:

The pattern for the glob() function can be relative and absolute. If it is relative, paths are searched from the current directory. If you want to search them in other directory, you need either change the current directory (which affects other parts of your program) or pass a concatenation of the escaped root directory and a pattern:

   glob.glob(os.path.join(glob.escape(root_dir), pattern))

Most code (even in the stdlib and tools) forget to escape the root directory. It works only until it does not contain metacharacters ('*?[').

When you need paths relative to the root directory, you need to "remove" the root_dir prefix from results (using os.path.relpath() at best).

The proposed PR adds two new parameters in glob.glob() and glob.iglob(): root_dir and dir_fd.

root_dir specifies the root directory for relative pattern. Its effect is the same as chdir before calling glob(). It is similar to the root_dir parameter of shutil.make_archive. For example, you can add py-files in the specified directory to the ZIP archive by:

    with zipfile.ZipFile(archive, 'w') as zf:
        for filename in glob.glob('**/*.py', recursive=True, root_dir=root_dir):
            zf.write(os.path.join(root_dir, filename), arcname=filename)

Adding to archive and copying are simpler if you have paths relative to the specified directory.

The dir_fd parameter is similar to root_dir, but it specifies the root directory as an open directory descriptor instead of a path (as in many os functions). It adds security (nobody can rename and replace the root directory in process) and performance (because of shorter paths).

root_dir and dir_fd can be combined. root_dir is relative to dir_fd and the pattern is relative to root_dir.

If root_dir is absolute, dir_fd is ignored. If the pattern is absolute, root_dir and dir_fd are ignored.

components: Library (Lib)
messages: 352223
nosy: serhiy.storchaka
priority: normal
severity: normal
status: open
title: Add the root_dir and dir_fd parameters in glob.glob()
type: enhancement
versions: Python 3.9

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list