如何在python上快速从文件中获取值?
我想存储一个dict,并与其他脚本一起快速阅读 存储在dict中的数据,如{1:a,2:b,3:c,…}。我使用以下代码将dict存储在磁盘上:如何在python上快速从文件中获取值?,python,Python,我想存储一个dict,并与其他脚本一起快速阅读 存储在dict中的数据,如{1:a,2:b,3:c,…}。我使用以下代码将dict存储在磁盘上: with open(filename+,'w') as f: f.write(str(dict1)) 然后,我想在另一个python脚本中使用键[3,7,9…]获取值 它必须读取整个文件吗?它浪费了很多时间 我找到了mmap,但我不知道如何使用它。如果您想从存储在磁盘上的对象(而不是整个字典)中读取单个项目,您需要某种类型的数据库 该模块是
with open(filename+,'w') as f:
f.write(str(dict1))
然后,我想在另一个python脚本中使用键[3,7,9…]获取值
它必须读取整个文件吗?它浪费了很多时间
我找到了
mmap
,但我不知道如何使用它。如果您想从存储在磁盘上的对象(而不是整个字典)中读取单个项目,您需要某种类型的数据库
该模块是一个简单的数据库工具,内置于Python中,用于字典。以下是文档中的一个示例:
import shelve
d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError
# if no such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = key in d # true if the key exists
klist = list(d.keys()) # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2] # this works as expected, but...
d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!
# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it
# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it
您不应该使用
str(dict)
转储到文件,也不应该为词典命名dict
来详细说明@chrisz的评论:您不想为词典命名dict
的原因是名称冲突。您使用名称dict()
@XiaXuehai实例化dicts,为什么不将另一个脚本导入原始脚本中?我测试了搁置。但是太慢了。打开它需要1.4秒。