1

我是一个 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')

文件

4

1 回答 1

2

我认为您正在使 JSON 与 CSV 变得过于复杂和混乱。向@thalesmallo 致敬,他在使用DictWriter课程时击败了我。尝试这个:

import csv
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()
response = client.connect_get()
data = response.json()
transactions = data['transactions'] # see https://plaid.com/docs/api/#data-overview

#Save the transactions JSON response to a csv file in the Python Projects directory
header = ("date", "_account", "name", "amount")
with open('transactions.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=header, extrasaction='ignore')
    writer.writeheader()
    for x in transactions:
        writer.writerow(x)
于 2016-12-15T05:11:49.227 回答