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 s
(self, name, arcname=None, recursive=True, *, filter=None)
| 2308 | print() |
| 2309 | |
| 2310 | def add(self, name, arcname=None, recursive=True, *, filter=None): |
| 2311 | """Add the file 'name' to the archive. 'name' may be any type of file |
| 2312 | (directory, fifo, symbolic link, etc.). If given, 'arcname' |
| 2313 | specifies an alternative name for the file in the archive. |
| 2314 | Directories are added recursively by default. This can be avoided by |
| 2315 | setting 'recursive' to False. 'filter' is a function |
| 2316 | that expects a TarInfo object argument and returns the changed |
| 2317 | TarInfo object, if it returns None the TarInfo object will be |
| 2318 | excluded from the archive. |
| 2319 | """ |
| 2320 | self._check("awx") |
| 2321 | |
| 2322 | if arcname is None: |
| 2323 | arcname = name |
| 2324 | |
| 2325 | # Skip if somebody tries to archive the archive... |
| 2326 | if self.name is not None and os.path.abspath(name) == self.name: |
| 2327 | self._dbg(2, "tarfile: Skipped %r" % name) |
| 2328 | return |
| 2329 | |
| 2330 | self._dbg(1, name) |
| 2331 | |
| 2332 | # Create a TarInfo object from the file. |
| 2333 | tarinfo = self.gettarinfo(name, arcname) |
| 2334 | |
| 2335 | if tarinfo is None: |
| 2336 | self._dbg(1, "tarfile: Unsupported type %r" % name) |
| 2337 | return |
| 2338 | |
| 2339 | # Change or exclude the TarInfo object. |
| 2340 | if filter is not None: |
| 2341 | tarinfo = filter(tarinfo) |
| 2342 | if tarinfo is None: |
| 2343 | self._dbg(2, "tarfile: Excluded %r" % name) |
| 2344 | return |
| 2345 | |
| 2346 | # Append the tar header and data to the archive. |
| 2347 | if tarinfo.isreg(): |
| 2348 | with bltn_open(name, "rb") as f: |
| 2349 | self.addfile(tarinfo, f) |
| 2350 | |
| 2351 | elif tarinfo.isdir(): |
| 2352 | self.addfile(tarinfo) |
| 2353 | if recursive: |
| 2354 | for f in sorted(os.listdir(name)): |
| 2355 | self.add(os.path.join(name, f), os.path.join(arcname, f), |
| 2356 | recursive, filter=filter) |
| 2357 | |
| 2358 | else: |
| 2359 | self.addfile(tarinfo) |
| 2360 | |
| 2361 | def addfile(self, tarinfo, fileobj=None): |
| 2362 | """Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents |