Python二进制文件。

2024-10-02 06:23:47 发布

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

嗨,我在python中使用unstack时遇到了一个问题

fileID= open('B1b1_t100000.beam','r');
npart = 1E6;
ncoord = 7;
coords = np.reshape(struct.unpack('d'*int(ncoord*npart),fileID.read()),(npart,ncoord));
fileID.close()

我得到了错误

Traceback (most recent call last):
File "transfer_lev_B1.py", line 30, in <module>
coords = np.reshape(struct.unpack('d'*int(ncoord*npart),fileID.read()),(npart,ncoord));
struct.error: unpack requires a string argument of length 56000000

我真的看不出问题出在哪里。文件字节大小为56000000。在先前的np=1E4尝试中,代码用于具有相同格式的不同文件(总行数较少)。但是当我转到一个包含更多行的更大的文件时会遇到问题。。你知道吗


Tags: 文件readnpopencoordsstructintunpack
1条回答
网友
1楼 · 发布于 2024-10-02 06:23:47

好吧,我解决了我的问题

    import struct
    import numpy as np
    import matplotlib.pyplot as plt

    if __name__ == '__main__':

        fileID= open('B1b1_t100000.beam','r');
        npart = 1E6;
        ncoord = 7;
        coords=np.fromfile('B1b1_t100000.beam',dtype=np.float64);
        coords=coords[:(npart*ncoord)];
        coords=np.reshape(coords,(npart,ncoord));
        fileID.close()

    #   Beam 1

        b1_x=coords[:,0];
        b1_y=coords[:,2];
        b1_z=coords[:,4];

        b1_px=coords[:,1];
        b1_py=coords[:,3];
        b1_deltap =coords[:,5];

        beam1=np.array([b1_x,b1_px,b1_y,b1_py,b1_z,b1_deltap,coords[:,6]],np.float64);
        beam1=beam1.T;

     #   Map applied and new coordinates calculated.

        x_mod=np.sqrt(foc)*coords[:,0];
        y_mod=np.sqrt(foc)*coords[:,2];

        px_mod=np.sqrt(defoc)*coords[:,1];
        py_mod=np.sqrt(defoc)*coords[:,3];

        beam1_mod=np.array([x_mod,px_mod,y_mod,py_mod,b1_z,b1_deltap,coords[:,6]],np.float64);
        beam1_mod=beam1_mod.T;

       #       -Check shape of matrix        

#print coords.shape
#    print (beam1_mod).shape
#    print beam1.shape
#    print 'beam1= \n', beam1
#    print 'modified \n', beam1_mod
#                          


#   New coordinates printed to binary file.

    fileMod=open("B1b1_t100000_mod.beam","w");
    beam1_mod.tofile(fileMod);
    fileMod.close()

相关问题 更多 >

    热门问题