简体   繁体   English

从二进制文件读取多行

[英]Reading multiple lines from binary file

I have a binary file, and I want to read its content, Here's the code 我有一个二进制文件,我想读取其内容,这是代码

with open ('file1', 'rb') as fp:

itemlist = pickle.load(fp)
print(itemlist)

and the code I am using to write to the file is 我用来写入文件的代码是

with open('file1', 'ab') as fp:

pickle.dump(training, fp)

The file contains many length 4 lists. 该文件包含许多长度为4的列表。 The problem is print(itemlist) is just printing the last list while I want all of them to convert to 2-D numpy array.I can even see the file size increasing gradually with every append call. 问题是print(itemlist)只是打印最后一个列表,而我希望它们都转换为二维numpy数组。我什至可以看到每次追加调用时文件大小都会逐渐增加。

How can I do it? 我该怎么做?

If you have many length 4 lists, you should dump and load them as a list of length 4 lists. 如果您有很多长度为4的列表,则应将其转储并加载为长度为4的列表。 Otherwise you would have to call pickle.load repeatedly until the file is exhausted. 否则,您将不得不反复调用pickle.load直到文件耗尽。

Build the 2d list first and after you save it. 保存后,请先构建2d列表。 In this way, you don't need to write/read multiple times the file. 这样,您无需多次写入/读取文件。

For example: 例如:

   import pickle
   training = []

   list1 = [2,4,5,6,7,7,2,6]
   list2 = [5,6,53,6,75,3,53,65]
   list3 = [46,89,24,64,243,25,6]
   list4 = [78,875,24,24,64,363,25]

   training.append(list1)
   training.append(list2)
   training.append(list3) 
   training.append(list4)

   with open('file1', 'ab') as fp:
       pickle.dump(training, fp)


   with open ('file1', 'rb') as fp:
      itemlist = pickle.load(fp)
      print(itemlist)

The output: 输出:

  [[2,4,5,6,7,7,2,6], [5,6,53,6,75,3,53,65], [46,89,24,64,243,25,6], [78,875,24,24,64,363,25]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM