Problems with "Tarfile.close()"

Ethan Furman ethan at stoneleaf.us
Fri Dec 20 10:41:51 EST 2019


On 12/20/2019 04:19 AM, Dr Rainer Woitok wrote:

> One of my Python scripts basically does the following:
> 
> source = tarfile.open(name=tar_archive  , mode='r|*')
> dest   = tarfile.open(fileobj=sys.stdout, mode='w|', format=fmt)
> 
>   .
>   .
>   .
> 
> source.close()
> dest.close()
> 
> In an attempt to move my Python scripts  from Python 2.7 to Python 3.6 I
> ran into the problem  that under Python 3.6  the call to  "dest.close()"
> fails:
> 
> Traceback (most recent call last):
>   File ".../tar_archive.copy", line 137, in <module>
>   dest.close()
>   File "/usr/lib64/python3.6/tarfile.py", line 1742, in close
>   self.fileobj.close()
>   File "/usr/lib64/python3.6/tarfile.py", line 467, in close
>   self.fileobj.write(self.buf)
> TypeError: write() argument must be str, not bytes

In Python 3 `sys.stdout` is a character interface, not bytes.

There are a couple solutions to the Python 3 aspect of the problem here:

   https://stackoverflow.com/q/908331/208880

If those answers do not work on Python 2 you'll need to detect which version you are on and act appropriately, perhaps hiding that bit of complexity in a function or class.

--
~Ethan~


More information about the Python-list mailing list