【问题标题】:How to decode binary file with " for index, line in enumerate(file)"?如何使用“for index, line in enumerate(file)”解码二进制文件?
【发布时间】:2016-10-04 20:44:26
【问题描述】:

我在file1.py 中打开一个非常大的二进制文件,我在 Python 3.5 中打开:

with open(pathname, 'rb') as file:
    for i, line in enumerate(file):
        # parsing here

但是,我自然会得到一个错误,因为我正在以二进制模式读取文件,然后创建一个字节列表。然后使用 for 循环,您将字符串与字节进行比较,此处代码失败。

如果我是在单独的行中阅读,我会这样做:

with open(fname, 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

但是,我使用的是for index, lines in enumerate(file):。在这种情况下正确的方法是什么?我要解码下一个对象吗?

这是我正在运行的实际代码:

with open(bam_path, 'rb') as file:
    for i, line in enumerate(file):
        line_data=pd.DataFrame({k.strip():v.strip()
            for k,_,v in (e.partition(':')
                for e in line.split('\t'))}, index=[i])

这是错误:

Traceback (most recent call last):                                                                                                
  File "file1.py", line 18, in <module>                                                                                        
    for e in line.split('\t'))}, index=[i])                                                                                       
TypeError: a bytes-like object is required, not 'str' 

【问题讨论】:

  • 为什么你希望二进制文件有行?
  • @matthias 这是一种以二进制压缩的制表符分隔的文本格式。上面的怎么打开?这是一个巨大的文件,500 GB 左右。

标签: python python-3.x binary decode enumerate


【解决方案1】:

您可以将带有解码行的生成器提供给enumerate

for i, line in enumerate(l.decode(errors='ignore') for l in f):

解码后产生f 中的每一行的技巧。我添加了errors='ignore',因为使用r 打开失败且起始字节未知。

顺便说一句,在bytes 上操作时,您可以将所有字符串文字替换为字节文字,即:partition(b':')split(b'\t') 并使用bytes 完成您的工作(很确定 pandas 可以正常使用它们) .

【讨论】:

  • 该文件最初是一个巨大的 (~500 GB) 制表符分隔的文本文件,现在是二进制文件。你会怎么打开这个?
  • 尝试仅使用r 打开会出现此错误:文件“bam_file.py”,第 15 行,在 for i,line in enumerate(l.decode() for l in file ):文件“bam_file.py”,第 15 行,在 中为 i,在枚举中的行(l.decode() 为文件中的 l):文件“/nfs/sw/python/python-3.5.1/lib /python3.5/codecs.py", line 321, in decode (result, used) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1 : 无效的起始字节
  • 我明白了,输入字符串的一部分显然无法转换。我会选择l.decode(errors='ignore') for l in f 打开文件。提供生成器还可以确保内容不会全部加载到内存中。
  • 这是我使用l.decode(errors='ignore') 得到的错误:File "/nfs/sw/python/python-3.5.1/lib/python3.5/codecs.py", line 321, in decode (结果,消耗) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
  • 你又用rb打开了文件?
猜你喜欢
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多