python - 将一个 FOR 循环中的字典结果写入 JSON 文件
问题描述
标题可能具有误导性,我想不出更好的表达方式:(。
我正在尝试将字典键和值写入 JSON 格式的 JSON 文件。
例子:
{
key1: value1
key2: value1
},
{
key1: value2
key2: value2
}
等等等等。
我试图在 FOR 循环中实现这个结果。
这是我拥有的当前代码:
for row in CSVR:
if totalCSV == 0:
# Not important for this question
else:
soup = BeautifulSoup(row[0], "html.parser") # Parsing results from CSV file using BeautifulSoup
confirmationNumber = remover(getConfirmationNumber(soup)) # Get confirmation number from a person
answersQuestions = remover(getQuestionsAndAnswers(soup)) # Get their question
answersQuestions = answersQuestions.strip() # Strip leading or trailing spaces
aa = {
"Confirmation Number": confirmationNumber,
"Message": answersQuestions
}
with open(bdPath, "w") as f:
json.dump(aa, f, indent = 4) # Write to JSON file
aa是我正在使用的字典。变量ConfirmationNumber和answersQuestions取决于 FOR 循环。
在我正在编写结果的文件中,我只获得了 FOR 循环的最后一个结果,而不是所有结果。
如果有办法,我该如何解决这个问题和/或使这个代码更好?
解决方案
aa
您需要在循环之后编写 JSON 文件并通过将它们“存储”在列表中来跟踪:
results = []
for row in CSVR:
if totalCSV == 0:
# Not important for this question
else:
soup = BeautifulSoup(row[0], "html.parser") # Parsing results from CSV file using BeautifulSoup
confirmationNumber = remover(getConfirmationNumber(soup)) # Get confirmation number from a person
answersQuestions = remover(getQuestionsAndAnswers(soup)) # Get their question
answersQuestions = answersQuestions.strip() # Strip leading or trailing spaces
results.append({
"Confirmation Number": confirmationNumber,
"Message": answersQuestions
})
with open(bdPath, "w") as f:
json.dump(results, f, indent = 4) # Write to JSON file
推荐阅读
- c# - 将特定数据库中的特定 SQL Server 表保存为 Excel 文件格式的自动化流程日常工作
- html - 我的 div 容器随着浏览器不断缩小
- c# - 在派生的泛型实例上调用静态扩展方法
- javascript - 如何从下表中删除一行?
- java - 由 Java 调用时出现 R 语言错误
- python - Pandas 基于列计算顺序
- java - Java中的多个消费者生产者
- android - 从 Firebase 向 Android 设备发送通知时如何设置频道?
- java - 如何使用 Java 在 Selenium 中通过文本查找 Web 元素?
- ssrs-2008 - SSRS - 使用 LookupSet 表达式进行交互式排序