MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   用Python从Matlab中获取“ fread”是什么意思? (https://www.labfans.com/bbs/showthread.php?t=23081)

poster 2019-12-10 20:30

用Python从Matlab中获取“ fread”是什么意思?
 
我对Matlab几乎一无所知,需要将一些解析例程转换为Python。它们是用于大型文件,这些文件本身又被分为“块”,而从文件顶部的校验和开始,我一直很困难。

Matlab在这里到底发生了什么?

status = fseek(fid, 0, 'cof'); fposition = ftell(fid); disp(' '); disp(['** Block ',num2str(iBlock),' File Position = ',int2str(fposition)]); % ----------------- Block Start ------------------ % [A, count] = fread(fid, 3, 'uint32'); if(count == 3) magic_l = A(1); magic_h = A(2); block_length = A(3); else if(fposition == file_length) disp(['** End of file OK']); else disp(['** Cannot read block start magic ! Note File Length = ',num2str(file_length)]); end ok = 0; break; end fid是当前正在查看的文件iBlock是您所在文件中的“阻止”对象的计数器

magic_l和magic_h稍后将与校验和相关,这是该代码(直接从上面的代码执行):

disp(sprintf(' Magic_L = %08X, Magic_H = %08X, Length = %i', magic_l, magic_h, block_length)); correct_magic_l = hex2dec('4D445254'); correct_magic_h = hex2dec('43494741'); if(magic_l ~= correct_magic_l | magic_h ~= correct_magic_h) disp(['** Bad block start magic !']); ok = 0; return; end remaining_length = block_length - 3*4 - 3*4; % We read Block Header, and we expect a footer disp(sprintf(' Remaining Block bytes = %i', remaining_length)); [LIST][*] %08X和hex2dec东西怎么了?[*]另外,为什么指定3*4而不是12 ?[/LIST]确实,我想知道如何复制[A, count] = fread(fid, 3, 'uint32');在Python中,因为io.readline()只是提取文件的前3个字符。抱歉,如果我在这里缺少要点。只是在文件上使用io.readline(3)似乎会返回它不应该返回的内容,并且我不明白在可能很长的情况下, block_length如何适合单个字节。

感谢您阅读本文。希望您能理解我想知道的内容! (任何见解都值得赞赏。)



[B]回答:[/B]

从[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fread.html"]fread[/URL]的[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fread.html"]文档中[/URL] ,它是读取二进制数据的功能。第二个参数指定输出向量的大小,第三个参数指定读取的项的大小/类型。

为了在Python中重新创建它,可以使用[URL="http://docs.python.org/3.1/library/array.html#module-array"]array[/URL]模块:

f = open(...) import array a = array.array("L") # L is the typecode for uint32 a.fromfile(f, 3) 这将会读取读取从文件中的三个UINT32值f ,这是在提供a之后。从[URL="http://docs.python.org/3.1/library/array.html#array.array.fromfile"]fromfile[/URL]的文档中:
[INDENT]从文件对象f中读取n项(作为机器值)并将其附加到数组的末尾。如果少于n个可用项目,则会引发EOFError,但可用项目仍将插入到数组中。 f必须是真正的内置文件对象;使用read()方法可以完成其他任务。

[/INDENT]数组实现序列协议,因此支持与列表相同的操作,但是您也可以使用.tolist()方法从数组创建普通列表。



[url=https://stackoverflow.com/questions/2146031]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 04:59

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.