我想選擇我的列表的任何部分,並在編程時保存無論如何選擇並保存數組的任何部分?
因此我尋找一個像f.save [i:j]的命令;
f = open ("text.txt","w")
f.write("123456789") **thats nine bit and ı wanna selec between second and fifth bit **
a = f.save[2:5]
類似的東西
我想選擇我的列表的任何部分,並在編程時保存無論如何選擇並保存數組的任何部分?
因此我尋找一個像f.save [i:j]的命令;
f = open ("text.txt","w")
f.write("123456789") **thats nine bit and ı wanna selec between second and fifth bit **
a = f.save[2:5]
類似的東西
您可以使用pickle,其序列化陣列(和其他Python對象),並將其保存到一個文件中。它還加載文件並反序列化內容,發出字典。閱讀文檔。你也可以使用它的一個實現,即shelve或persistent dict,它也支持json和其他格式,而不是pickle
。
你也可以使用數據庫像sqlite或只是一個純文本文件,並使用自己的實現。
I tried but pickle does not working for me
什麼是不工作?請多考慮一下你的問題。嘗試使用擱置:
>>> import shelve
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> db = shelve.open('/path/to/my/database/file.db', writeback=True) # Notice the file must already exist
>>> db['a'] = a[2:5]
>>> db.close()
>>> quit()
# New interpreter is opened
>>> import shelve
>>> db = shelve.open('/path/to/my/database/file.db', writeback=True)
>>> db['a']
[3, 4, 5]
ı更新了問題 –
如果[]是隨機字符串,該怎麼辦?任何問題? a = [random.uniform(10,100)for i range(1000) –
編號'a'可以是'pickle'支持的任何python對象。閱讀答案中鏈接的文檔。 – Alex
import pickle
f = open("text.txt","w")
pickle.dump("123456789"[2:5], f)
f.close()
是什麼意思保存? – RiaD
你的意思是保存到磁盤?你應該使用泡菜模塊。 – YXD