参数1必须有一个“写”方法 - 从json创建csv文件

问题描述 投票:1回答:1

我正在使用boto3Python调用AWS API,我正在编写JSONJSONfile的响应。我然后尝试将JSON文件转换为CSV文件。当我尝试使用csv writer()方法执行此操作时,出现上述错误,我不确定原因。

码:

def ResponseConvert():
    dynamo = boto3.client('dynamodb')

    response = dynamo.scan(
    TableName='XXXX'
    )

    with open('vuln_data.json', 'w') as outfile:
        json.dump(response, outfile, indent=4)

    f = open('vuln_data.json')
    data = json.load(f)
    f.close()

    f = csv.writer(open('vuln_data.csv', 'wb+'))

    f.writerow(data.keys())
    for row in data:
        f.writerow(row.values())

ResponseConvert()

追溯:

Traceback (most recent call last):
  File "response_convert.py", line 21, in <module>
    ResponseConvert()
  File "response_convert.py", line 19, in ResponseConvert
    f.writerow(row.values())
AttributeError: 'unicode' object has no attribute 'values'
python json csv
1个回答
1
投票

CSV编写者期望文件句柄,而不是文件名。

with open('filename.csv', 'w') as f:
    writer = csv.writer(f)
    ...

顺便说一句,你可能想要一个DictWriter。不要依赖keysvalues匹配的顺序。

© www.soinside.com 2019 - 2024. All rights reserved.