[英]Get the string representation of an object without loading the object into memory
[英]Read/Write/Updating object without loading the object to memory
我一直在嘗試使用 Klepto package 將我的 object 寫入/讀取/更新到硬盤,旨在避免我在使用我的數據集訓練我的 model 時遇到的“內存不足”問題。 根據我的理解,使用 Klepto 我可以將我的數據存儲為基於鍵值的機制。 但是我不太確定當我從 klepto.archieve 加載數據時是否可以直接更新 object。 更新時,例如向列表中添加一個值,同時保持不要將 object 直接加載到 memory 以避免“內存不足”問題。
這是一個關於保存數據的示例(如果這也不是設置它的正確方法,請糾正我):
from klepto.archives import *
arch = file_archive('test.txt')
arch['a'] = [3,4,5,6,7]
arch.dump()
arch.pop('a')
我是klepto
的作者。 如果我明白你想要什么,那么看起來你已經正確設置了它。 關鍵關鍵字已cached
。 如果您使用cached=True
,那么存檔將被構造為內存中的緩存,並帶有手動同步的文件后端。 如果您使用cached=False
,則沒有內存緩存......您只需直接訪問文件存檔。
Python 3.7.16 (default, Dec 7 2022, 05:04:27)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import *
>>> arch = file_archive('test.txt', cached=True)
>>> arch['a'] = [3,4,5,6,7]
>>> arch.dump() # dump to file archive
>>> arch.pop('a') # delete from memory
[3, 4, 5, 6, 7]
>>> arch
file_archive('test.txt', {}, cached=True)
>>> arch.load('a') # load from file archive
>>> arch
file_archive('test.txt', {'a': [3, 4, 5, 6, 7]}, cached=True)
>>>
>>> arch2 = file_archive('test.txt', cached=True)
>>> arch2
file_archive('test.txt', {}, cached=True)
>>> arch2.load() # load from file archive
>>> arch2
file_archive('test.txt', {'a': [3, 4, 5, 6, 7]}, cached=True)
>>>
>>> arch3 = file_archive('test.txt', cached=False)
>>> arch3 # directly access file-archive
file_archive('test.txt', {'a': [3, 4, 5, 6, 7]}, cached=False)
>>>
您還可以操作存檔中已有的對象...不幸的是,對於cached=False
,需要將 object 加載到 memory 中進行編輯(由於缺少存檔內編輯的實現,您只能替換中的對象cached=False
存檔)。
>>> arch2
file_archive('test.txt', {'a': [3, 4, 5, 6, 7]}, cached=True)
>>> arch2['a'].append(8) # edit the in-memory object
>>> arch2
file_archive('test.txt', {'a': [3, 4, 5, 6, 7, 8]}, cached=True)
>>> arch2.dump('a') # save changes to file-archive
>>> arch3
file_archive('test.txt', {'a': [3, 4, 5, 6, 7, 8]}, cached=False)
>>>
>>> arch3['a'] = arch2['a'][1:] # replace directly in-file
>>> arch3
file_archive('test.txt', {'a': [4, 5, 6, 7, 8]}, cached=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.