[英]Python3: f.read() in Tarfile returns bytes instead of a file-like object and it passes empty file
I am having issue with passing file-like object of a tgz file in Python.我在通过 Python 中的 tgz 文件的类似文件 object 时遇到问题。 here is how my code looks like:
这是我的代码的样子:
backup = tarfile.open(backup_file, mode='r:gz')
for f in backup.getmembers():
if f.name.endswith('.xml'):
ff = f.name
backupff = backup.extractfile(ff)
if backupff:
backupobj = backupff.read()
backup.close()
The problem arises from问题源于
backupobj = backupff.read()
and it gives this error:它给出了这个错误:
AttributeError: 'bytes' object has no attribute 'read'
AttributeError: 'bytes' object 没有属性 'read'
I don't have such a problem when dealing with zip files.我在处理 zip 文件时没有这样的问题。
@AKX, you are right that this not the code I'm running. @AKX,你说得对,这不是我正在运行的代码。 The real code are very big and I am not sure anyone has time to look into it.
真正的代码非常大,我不确定是否有人有时间研究它。
Anyway, when I run the main function, I receive this error:无论如何,当我运行主 function 时,我收到此错误:
file_read = file.read
file_read = file.read
AttributeError: 'bytes' object has no attribute 'read'
AttributeError: 'bytes' object 没有属性 'read'
Here is file.read part:这是 file.read 部分:
def sendfile(self, file, offset=0, count=None):
"""Borrowed from https://github.com/python/cpython/blob/3.6/Lib/socket.py
and adapted to our needs
"""
self._check_sendfile_params(file, offset, count)
if self.request.gettimeout() == 0:
raise ValueError("non-blocking sockets are not supported")
if offset:
file.seek(offset)
blocksize = min(count, 8192) if count else 8192
total_sent = 0
# localize variable access to minimize overhead
file_read = file.read
sock_send = self.request.send
I'm quite positive that's not the code you're running, or not the environment you're running in. I can't reproduce this with Python 3.8:我很肯定这不是您正在运行的代码,也不是您正在运行的环境。我无法使用 Python 3.8 重现这一点:
$ echo aaa > 1.xml
$ echo bbb > 2.xml
$ tar czvf a.tar.gz *.xml
a 1.xml
a 2.xml
$ cat x.py
import tarfile
backup_file = 'a.tar.gz'
with tarfile.open(backup_file, mode='r:gz') as backup:
for member in backup.getmembers():
if member.name.endswith('.xml'):
fh = backup.extractfile(member)
if fh:
content = fh.read()
print((member.name, content))
$ python3 x.py
('1.xml', b'aaa\n')
('2.xml', b'bbb\n')
I found the solution:我找到了解决方案:
There is no need to use following commands:无需使用以下命令:
if backupff:
backupobj = backupff.read()
This line is sufficient to assign the file to external user此行足以将文件分配给外部用户
backupff = backup.extractfile(ff)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.