python - 如何在 Python 3 中从磁盘读取和编辑列表?
问题描述
我有一个要附加到单独磁盘文件的字典列表。然后,我希望能够读取这个字典项目列表并将它们移动到不同文件中的其他列表。
import os
# List 'x' will auto-populate itself with hundreds of new dictionary items upon run - using x.append({'name': f'{var}', 'job': f'{var2}'}) etc.
x = []
i = input('Request: ')
if i == 'add to list':
with open('example list', 'a') as list:
list.write(x)
elif i == 'print list':
with open('example list', 'r') as list:
list.read(x)
print(list)
# in this next block, I would like to be able to move an item from the 'example list' list to a different list that is housed in a separate file
elif i == 'move item':
# 'n' requests an integer value to represent the index in the list
n = input('Which item do you want to move? ')
with open('example list', 'r') as list:
j = list[n]
# I want to delete 'j' from 'example list'
with open('other list', 'a') as other_list:
# I want to append 'j' to 'other list'
other_list.write(j)
print('example list')
我被困在这些列表项的阅读和移动上。我什至不能让它以很好的格式打印“示例列表”。我听说过泡菜模块,但我从未使用过它。我也明白,为了能够访问列表项和其中的后续字典键,可能需要将这些列表保存为 json 文件。任何帮助,将不胜感激。
解决方案
我想到了。使用 json 模块,我能够将列表转储到外部 json 文件:
x = []
with open('json list.json', 'w') as f:
json.dump(x, f)
然后我可以使用以下方法重新加载数据:
list1 = open('json list', 'r')
listread = list1.read()
data = json.loads(listread)
为了在列表之间移动项目,我使用了这个:
move_item = data[3]
del move_item
json.dumps(data)
move_to = open('other list'. 'a')
move_to.write(move_item)
list1.close()
move_to.close()
加载后,列表和其中的后续字典作为它们各自的对象保持不变,从而允许通过索引或键进行访问。谢谢大家,我综合了大家的建议。
推荐阅读
- reactjs - Retorno:TypeError:无法读取未定义的属性“长度”
- jquery - 通过 jQuery 向 Flask 发送不一致的数据类型请求
- python - 如何将所有固定消息插入文件?
- javascript - 使用 Puppeteer 将数据添加到非表单字段中
- r - 当折线图和条形图来自不同的数据框时,修复 ggplot 中的图例
- php - 在 mac osx big sur 上找不到“unicode/ubrk.h”文件
- node.js - 尽管 node.js 发生了许多变化,但仍不会消失的错误
- python - Python 使用 einsum 理解数组形状
- c# - ITMS-90809:不推荐使用 API 尝试使用 Xamarin iOS 部署 admob 横幅
- flutter - bulderFunctions 的 openContainer 之上的提供者