python - 从 BytesIO 解压缩 bz2 文件

标签 python csv paramiko

我想读取服务器中的bz2文件,将其解压并使用csv解析器读取,但仍然有错误;

    myfile = bz2.BZ2File(bio.read(), "rb")
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

import paramiko
from config import config
import bz2
import csv
import StringIO
from io import BytesIO
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(config.get('mrc_ssh', 'host'), username=config.get('mrc_ssh', 'user'))
sftp_client = ssh.open_sftp()
_file = sftp_client.open('/home/myfile.bz2')
bio = BytesIO(_file.read())
print bio
myfile = bz2.BZ2File(bio.read(), "rb")
reader = csv.DictReader(myfile)
for row in reader:
    print row

最佳答案

bz2.BZ2File文件名作为第一个参数。不是实际数据。

使用(如果您可以在本地存储文件):

myfile = bz2.BZ2File('/home/myfile.bz2', "rb")

或者使用一次性解压功能bz2.decompress

uncompressed_data = bz2.decompress(bio.read())

关于python - 从 BytesIO 解压缩 bz2 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236161/

相关文章:

Python paramiko.ssh_exception.SSHException : No existing session

python - 在 Windows 中安装 Scrapy 时遇到问题

python - 你如何使用循环根据键分配字典值

Python Paramiko - 运行命令

javascript - 上传CSV到meteor : _id not defined

python-3.x - python pandas 特殊字符作为分隔符

python - 连续从 Paramiko SSH exec_command 获取输出

python - 如何像 Openstack Swift 一样在 Python (Boto lib) 中获取 Amazon S3 存储桶的元数据/ header ?

python - 正则表达式区分 Windows 和 Linux 行尾字符

sql - 如何使用R语言处理50GB的大型CSV文件?