Skip to content

Commit 7633371

Browse files
authored
bpo-22021: Update root_dir and base_dir documentation in shutil (pythonGH-10367)
Also added an example in shutil in order to make more clear how they are to be used. Initially reported by Weinan Li on bpo.
1 parent 37eed5a commit 7633371

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

Doc/library/shutil.rst

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -570,12 +570,14 @@ provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
570570
available), or "xztar" (if the :mod:`lzma` module is available).
571571

572572
*root_dir* is a directory that will be the root directory of the
573-
archive; for example, we typically chdir into *root_dir* before creating the
574-
archive.
573+
archive, all paths in the archive will be relative to it; for example,
574+
we typically chdir into *root_dir* before creating the archive.
575575

576576
*base_dir* is the directory where we start archiving from;
577577
i.e. *base_dir* will be the common prefix of all files and
578-
directories in the archive.
578+
directories in the archive. *base_dir* must be given relative
579+
to *root_dir*. See :ref:`shutil-archiving-example-with-basedir` for how to
580+
use *base_dir* and *root_dir* together.
579581

580582
*root_dir* and *base_dir* both default to the current directory.
581583

@@ -727,6 +729,48 @@ The resulting archive contains:
727729
-rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
728730
729731
732+
.. _shutil-archiving-example-with-basedir:
733+
734+
Archiving example with *base_dir*
735+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736+
737+
In this example, similar to the `one above <shutil-archiving-example_>`_,
738+
we show how to use :func:`make_archive`, but this time with the usage of
739+
*base_dir*. We now have the following directory structure:
740+
741+
.. code-block:: shell-session
742+
743+
$ tree tmp
744+
tmp
745+
└── root
746+
└── structure
747+
├── content
748+
└── please_add.txt
749+
└── do_not_add.txt
750+
751+
In the final archive, :file:`please_add.txt` should be included, but
752+
:file:`do_not_add.txt` should not. Therefore we use the following::
753+
754+
>>> from shutil import make_archive
755+
>>> import os
756+
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
757+
>>> make_archive(
758+
... archive_name,
759+
... 'tar',
760+
... root_dir='tmp/root',
761+
... base_dir='structure/content',
762+
... )
763+
'/Users/tarek/my_archive.tar'
764+
765+
Listing the files in the resulting archive gives us:
766+
767+
.. code-block:: shell-session
768+
769+
$ python -m tarfile -l /Users/tarek/myarchive.tar
770+
structure/content/
771+
structure/content/please_add.txt
772+
773+
730774
Querying the size of the output terminal
731775
----------------------------------------
732776

0 commit comments

Comments
 (0)