我在Python中传递类似文件的tgz文件对象时遇到问题。我的代码是这样的:
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()
问题来自
backupobj = backupff.read()
它给出了这个错误:
属性错误:"字节"对象没有属性"读取"我在处理zip文件时没有遇到这样的问题。
更新
@AKX,你说得对,这不是我正在运行的代码。真正的代码非常大,我不确定是否有人有时间去研究它
不管怎样,当我运行主功能时,我会收到这个错误:
file_read=file.read
AttributeError:"bytes"对象没有属性"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
我很肯定这不是你正在运行的代码,也不是你运行的环境
$ 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'aaan')
('2.xml', b'bbbn')
我找到了解决方案:
无需使用以下命令:
if backupff:
backupobj = backupff.read()
这一行足以将文件分配给外部用户
backupff = backup.extractfile(ff)