调整大小numpy.memmapinp公司

2024-04-26 03:08:53 发布

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

调整大小的代码似乎可以工作,但程序所做的更改不会被保存。在

def test_resize_inplace():

    fA = np.memmap('A_r.npy', dtype='uint8', mode='w+', shape=(3,12))

    print "fA"
    print fA

    fA[2][0] = 42

    # resize by creating new memmap
    new_fA = np.memmap('A_r.npy', mode='r+', dtype='uint8', shape=(20,12))

    print 'fA'
    print fA

    print 'new_fA'
    print new_fA

另外,当我试图将调整大小的过程去掉时,它会在线压垮python解释器

^{pr2}$

代码如下:

def resize_memmap(fm,sz,tp):
    fm.flush()
    print fm.filename
    new_fm = np.memmap(fm.filename, mode='r+', dtype= tp, shape=sz)
    return new_fm

def test_resize_inplace():

    fA = np.memmap('A_r.npy', dtype='uint8', mode='w+', shape=(3,12))

    print "fA"
    print fA

    fA[2][0] = 42

    sz= (20,12)
    tp= 'uint8'

    new_fA= resize_memmap(fA,sz,type)
    new_fA[9][9]= 111

    print 'fA'
    print fA

    print 'new_fA'
    print new_fA

更新: 我试过了

def test_memmap_flush():
    fA = np.memmap('A_r.npy', dtype='uint8', mode='w+', shape=(3,12))

    print "fA"
    print fA

    fA[2][0] = 42

    fA.flush()

# fB = np.memmap('A_r.npy', dtype='uint8', mode='w+', shape=(3,12)) #fails
fB = np.memmap('A_r.npy', dtype='uint8', mode='r+', shape=(3,12))

    print "fB"
    print fB

    print "done"

但我不明白为什么我不能有w+模式?在

IOError: [Errno 22] invalid mode ('w+b') or filename: 'A_r.npy'


更新:

好吧,我明白。w+用于创建,r+用于读写。在


Tags: newfbmodedefnpfaprintshape
2条回答

文件可能在两次访问之间没有刷新。尝试将加载到with块中的文件对象传递给memmap:

with open('A_r.npy', 'w') as f:
    fA = np.memmap(f, ...
with open('A_r.npy', 'r') as f:
    fA = np.memmap(f, ...

答案:为什么出现IO Error: [Errno 22]?在

首先,我不得不承认,在大约六个月的时间里,这给我带来了一些小麻烦,为此我不得不求助于手工黑客。在

我终于找到了根本原因。在

此错误仅在Windows中出现(Unix没有对此产生异常)
,此时.memmap()-ed文件仍在另一个文件句柄下打开。在

del aMMAP # first ( does .flush() before closing the underlying fileHandle
#         # next, mmap again, with adjustments you need
aMMAP = np.memmap( ... )

希望这有助于
Credit goes to Michael Droettboom

相关问题 更多 >

    热门问题