Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by
(self, name, arcname=None, recursive=True, *, filter=None)
| 2140 | print() |
| 2141 | |
| 2142 | def add(self, name, arcname=None, recursive=True, *, filter=None): |
| 2143 | """Add the file `name' to the archive. `name' may be any type of file |
| 2144 | (directory, fifo, symbolic link, etc.). If given, `arcname' |
| 2145 | specifies an alternative name for the file in the archive. |
| 2146 | Directories are added recursively by default. This can be avoided by |
| 2147 | setting `recursive' to False. `filter' is a function |
| 2148 | that expects a TarInfo object argument and returns the changed |
| 2149 | TarInfo object, if it returns None the TarInfo object will be |
| 2150 | excluded from the archive. |
| 2151 | """ |
| 2152 | self._check("awx") |
| 2153 | |
| 2154 | if arcname is None: |
| 2155 | arcname = name |
| 2156 | |
| 2157 | # Skip if somebody tries to archive the archive... |
| 2158 | if self.name is not None and os.path.abspath(name) == self.name: |
| 2159 | self._dbg(2, "tarfile: Skipped %r" % name) |
| 2160 | return |
| 2161 | |
| 2162 | self._dbg(1, name) |
| 2163 | |
| 2164 | # Create a TarInfo object from the file. |
| 2165 | tarinfo = self.gettarinfo(name, arcname) |
| 2166 | |
| 2167 | if tarinfo is None: |
| 2168 | self._dbg(1, "tarfile: Unsupported type %r" % name) |
| 2169 | return |
| 2170 | |
| 2171 | # Change or exclude the TarInfo object. |
| 2172 | if filter is not None: |
| 2173 | tarinfo = filter(tarinfo) |
| 2174 | if tarinfo is None: |
| 2175 | self._dbg(2, "tarfile: Excluded %r" % name) |
| 2176 | return |
| 2177 | |
| 2178 | # Append the tar header and data to the archive. |
| 2179 | if tarinfo.isreg(): |
| 2180 | with bltn_open(name, "rb") as f: |
| 2181 | self.addfile(tarinfo, f) |
| 2182 | |
| 2183 | elif tarinfo.isdir(): |
| 2184 | self.addfile(tarinfo) |
| 2185 | if recursive: |
| 2186 | for f in sorted(os.listdir(name)): |
| 2187 | self.add(os.path.join(name, f), os.path.join(arcname, f), |
| 2188 | recursive, filter=filter) |
| 2189 | |
| 2190 | else: |
| 2191 | self.addfile(tarinfo) |
| 2192 | |
| 2193 | def addfile(self, tarinfo, fileobj=None): |
| 2194 | """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is |