每820字节保存到新fi

2024-05-11 03:36:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件(大小:20MB |二进制文件),需要每820字节解析一次,820字节的内容保存到一个新文件中,文件名是2字节和16字节标记之间的字符串(ASCII)。你知道吗

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
    ^ THE FILENAME COMES FROM HERE    ^

好吧,既然挑战已经被解释了(我希望)我现在所拥有的是:

#!/usr/bin/python

with open("file", "rb") as f:
    byte = f.read()
    if byte > 820:
        print "Reach the 1 record mark on the File you have defined "

但我也看到了一种可能性:

for f.read(820) in file:
   a = f.read()
   b = open("Iam_from_2_to_16_byte_string", w)
   b.write(a)
   b.close

好吧,我不知道的是如何迭代的前820字节,然后下一个820字节和下一个,直到文件和ofc的最难的部分,是抓取每次我做这个新文件的2至16字节的缓冲区,并使用它作为一个文件名在每个新文件我有820字节。你知道吗


Tags: 文件the字符串标记内容read字节文件名
2条回答

Python的file方法read()有一个option参数,用于设置要读取的字节数。它还将filepointer保留在读取的字节的末尾,以便下一个调用将在上次读取的最后一个字节之后启动:

n = 820
with open("file", "rb") as f:
    while True:
        data = f.read(n)
        if not data:
            break
        # do stuff with data.
        # for example, get a filename
        filename = str(data[2:16])

在820步中迭代文件内容,直到达到EOF。你知道吗

^{} function可以传递一个函数和一个sentinel,用它来读取820字节块的文件:

for chunk in iter(lambda: f.read(820), ''):
    # chunk is now 820 bytes long, until the last chunk which *could* be shorter.

每次迭代都会调用lambda函数,读取820字节,直到f.read(820)返回一个空字符串(表示EOF)。你知道吗

块只是一个字符串,因此可以使用切片来获取文件名:

filename = chunk[2:16]

一起使用:

with open("file", "rb") as f:
    for chunk in iter(lambda: f.read(820), ''):
        open(chunk[2:16], 'wb').write(chunk)

相关问题 更多 >