【发布时间】:2017-04-30 12:44:09
【问题描述】:
我是一个 Python 菜鸟,正在使用 Plaid API 来获取银行交易。我希望每笔交易都是自己的行,我只想为每条记录提取四个值:日期、_account、名称和金额,并用该数据填充一个 CSV 文件。我有以下代码填充单行 CSV(还附加了 JSON 文件)。在一些谷歌搜索之后,我似乎无法弄清楚我在寻找什么,例如如何做到这一点。非常感谢任何帮助。
import csv
#Configuration
from plaid import Client
Client.config({
'url': 'https://api.plaid.com'
})
#Connect to Plaid
from plaid import Client
from plaid import errors as plaid_errors
from plaid.utils import json
client = Client(client_id='test_id', secret='test_secret')
account_type = 'suntrust'
try:
response = client.connect(account_type, {
'username': 'plaid_test',
'password': 'plaid_good'
})
except plaid_errors.PlaidError:
pass
else:
connect_data = response.json()
#Get transactions from Plaid
response = client.connect_get()
transactions = response.json()
#Save the transactions JSON response to a csv file in the Python Projects directory
with open('transactions.csv', 'w') as outfile:
json.dump(transactions, outfile)
csvfile = open('transactions.csv', 'r')
jsonfile = open('transactions.json', 'w')
fieldnames = ("date", "_account","name","amount")
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
【问题讨论】:
-
你的问题是什么?
-
查看 Python 文档中的 DictWriter 类。将 JSON 转换为 csv 会更简单。
-
json 代码更能解决你的问题
-
John Zwinck - 我应该在我的帖子中更清楚,我正在尝试填充一个多行 CSV 文件,而不是我现在得到的一行,并且只填充 4 列JSON 文件。
-
这是一个格式错误的 JSON。有多个带有字符串和 int 条目的名称字段。