.. method:: TarFile.addfile(tarinfo, fileobj=None)
- Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
- it should be a :term:`binary file`, and
- ``tarinfo.size`` bytes are read from it and added to the archive. You can
+ Add the :class:`TarInfo` object *tarinfo* to the archive. If *tarinfo* represents
+ a non zero-size regular file, the *fileobj* argument should be a :term:`binary file`,
+ and ``tarinfo.size`` bytes are read from it and added to the archive. You can
create :class:`TarInfo` objects directly, or by using :meth:`gettarinfo`.
+ .. versionchanged:: 3.13
+
+ *fileobj* must be given for non-zero-sized regular files.
+
.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
self.addfile(tarinfo)
def addfile(self, tarinfo, fileobj=None):
- """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
- given, it should be a binary file, and tarinfo.size bytes are read
- from it and added to the archive. You can create TarInfo objects
- directly, or by using gettarinfo().
+ """Add the TarInfo object `tarinfo' to the archive. If `tarinfo' represents
+ a non zero-size regular file, the `fileobj' argument should be a binary file,
+ and tarinfo.size bytes are read from it and added to the archive.
+ You can create TarInfo objects directly, or by using gettarinfo().
"""
self._check("awx")
+ if fileobj is None and tarinfo.isreg() and tarinfo.size != 0:
+ raise ValueError("fileobj not provided for non zero-size regular file")
+
tarinfo = copy.copy(tarinfo)
buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
pax_headers={'non': 'empty'})
self.assertFalse(f.closed)
+ def test_missing_fileobj(self):
+ with tarfile.open(tmpname, self.mode) as tar:
+ tarinfo = tar.gettarinfo(tarname)
+ with self.assertRaises(ValueError):
+ tar.addfile(tarinfo)
+
class GzipWriteTest(GzipTest, WriteTest):
pass
tar = tarfile.open(fileobj=bio, mode='w', format=tarformat)
tarinfo = tar.gettarinfo(tarname)
try:
- tar.addfile(tarinfo)
+ with open(tarname, 'rb') as f:
+ tar.addfile(tarinfo, f)
except Exception:
if tarformat == tarfile.USTAR_FORMAT:
# In the old, limited format, adding might fail for
replaced = tarinfo.replace(**{attr_name: None})
with self.assertRaisesRegex(ValueError,
f"{attr_name}"):
- tar.addfile(replaced)
+ with open(tarname, 'rb') as f:
+ tar.addfile(replaced, f)
def test_list(self):
# Change some metadata to None, then compare list() output
--- /dev/null
+Add parameter *fileobj* check for :func:`tarfile.addfile()`