我正在使用从 WEB-api 返回的大量数据。下面的函数调用 API 22 次,将 json 解码并加载为 python 格式。然后我将结果存储在一个 22 页的大列表中,每 100 个艺术品作为数据。
fourteen_list = return_14th_century_works_list()
为了限制必要的 API 调用,我想构建一个函数,在该列表不存在时将该列表存储为文件,当它存在时,我想从我的计算机加载该文件。我想出了以下内容:
with open('fourteenth_century_list.txt', 'w') as fourteenth_century_file:
print(fourteen_list, file=fourteenth_century_file)
try:
with open('fourteenth_century_list.txt', 'r') as fourteenth_century_file:
fourteenth_list_cache = fourteenth_century_file.read()
count_objects(fourteenth_list_cache)
except FileNotFoundError:
fourteenth_list = return_14th_century_works_list() Calls API again
count_objects(fourteen_list)
我使用 count_objects 函数来检查是否一切正常,但是在 try block 中打开的文件似乎并没有以我保存它的方式返回;当我运行这段代码时,try block 中的函数调用返回类型错误。对我来说,这表明从磁盘打开的文件的格式与我直接从 API 加载它的格式有所不同。
当我用我的列表的非缓存版本调用函数 count_objects() 时,所以 fourteen_list 在这种情况下工作正常。
with_open(filename, 'w') 然后 with_open(filename, 'r') 是否会改变您的数据,如果不是,我做错了什么?
请您参考如下方法:
这里的问题是,当您将字典列表打印 到一个文件时,您创建了该列表的字符串表示形式。然后您读回该字符串并将其传递给 count_objects(),但这会失败,因为它需要一个字典列表,而不是一个大字符串。
比打印更好的方法是将列表序列化以支持 JSON - 这将保留其结构。您还希望在从 API 检索数据后将列表写入 except block 中的缓存。
import json
try:
with open('fourteenth_century_list.json', 'r') as fourteenth_century_file:
fourteenth_list_cache = json.load(fourteenth_century_file)
count_objects(fourteenth_list_cache)
except FileNotFoundError:
# Calls API again
fourteenth_list = return_14th_century_works_list()
count_objects(fourteen_list)
# Cache the API data
with open('fourteenth_century_list.json', 'w') as fourteenth_century_file:
json.dump(fourteen_list, fourteenth_century_file)
